Tuesday, March 6, 2012

What is the difference between Struct and class in C++?

   The basic difference between struct and class in C++ is that by default all data member functions and member variabels are private in class  where as in struct it is public. Except this every thing is same for struct and class. All C++ concepts like polymorphism, inheritance etc works fine with struct also.

Basic example:

struct structClass
{
        int x; // defualt public
    public:
        structClass();
};

structClass::structClass()  // constructor
{
    x=0;
}

class classC
{
    int x; //defualt private
    public:
        classC();
};

classC::classC()  // constructor
{
    x=0;
}

int main()
{
    structClass sC;
    sC.x =10; // Legal as it is a struct and not a class
    classC cC;
//  cC.x = 10; // Illegal as it is a class and default specifier is private
}


Example for Inheritance:
struct base
{
    public:
        virtual void display()
        {
            cout<<"this is base class\n";
        }
};

class derived: public base
{
    public:
        void display()
        {
            cout<<"this is derived class\n";
        }
};

int main()
{
    base b1;
    derived d;
    base &b = d;
    b.display();
}
In the above sample code, base class is of type structure and derived class is of type c++ class. This also works fine in C++.

No comments:

Popular Posts