About Me

My photo
Posting here few basic programs. I prefer using C++. Trying to keep it error free. Feel free to point any of them. Thanks for visiting. You can copy paste code directly from here.
Showing posts with label Class vs Structure. Show all posts
Showing posts with label Class vs Structure. Show all posts

Thursday, 22 September 2011

/* Struct vs Class

Program to show there aren't many differences between a structure and a class

COMMENTS are shown in bold and italics*/


#include<iostream.h>
#include<conio.h>



class Demo2                                      //class
{
    public:                                              //public label
        void print()
        {
            cout<<"\n\n For the class\n\n Enter a, b and c : ";
            cin>>a>>b>>c;
            cout<<"\n a= "<<a<<" b = "<<b<<" c= "<<c;
        }
       

    private:
        int a;
        int b;

    protected:
        int c;
};
Demo2 a2;                              // object created for the class



struct Demo1                        
                                       

{
    public:                                             //see this has labels as a class
        void print()                                  // has functions
        {
            cout<<"\n\nFor the structure\nEnter x, y and p : ";
            cin>>x>>y>>p;
            cout<<"\nx= "<<x<<" y = "<<y<<" p= "<<p;
        }
        Demo1();

                             /* even has constructors & destructors although i have shown a constructor only . A constructor is a special function having same name of the class */

    private:
        int x;
        int y;

    protected:
        int p;
};
Demo1 a1;                   

//object of structure defined in the same way as for a class                




Demo1::Demo1()             /*constructor declaration outside structure as can be done for a class*/
{
    x = y = p = 0;
    cout<<"\nThis shows constructor working for struct\n"<<"\n x= "<< x <<" y = "<< y <<" p= "<< p;
}



int main()
{
    a1.print();                                //calling structure object
    a2.print();                                //calling class object         
    getch();
    return 0;
}

Sample Output: