Sunday, 7 August 2016

DIFFERENCE BETWEEN CLASS AND STRUCT IN C++

 
There are few differences between class and structure in C++.

1.       When access specifier is not specified manually then all members of the class is private, where as in structure all members are public.

Consider the following example

 
class myClass
{
 int a; // a is private
};

class myStruct
{
 int a; // a is public 
};






2.       During inheritance use of class and struct will make difference in access specifier.
a.       When derived one is specified as class, then public member of the base class is private to the derived class.


   
class myClass
{
 public:
 int a; 
};

class Derived : myClass
{
 int b; 
};

int main()
{
 Derived d;
 d.a=10; // Compilation error, a is private because Derived is mentioned as class
}



b.       When derived one is specified as struct, then public member of the base class is public to the derived class.

class myClass
{
 public:
 int a; 
};

struct Derived : myClass
{
 int b; 
};

int main()
{
 Derived d;
 d.a=10; // a is public because Derived is mentioned as struct
}


3.       Keyword ‘class’ can be used in place of typename for templates, where as struct cannot be used in place of typename.


template <class T>
class myClass
{
 T a;
};