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.

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*/


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

        int a;
        int b;

        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 : ";
            cout<<"\nx= "<<x<<" y = "<<y<<" p= "<<p;

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

        int x;
        int y;

        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         
    return 0;

Sample Output:

No comments:

Post a Comment