Dropping egg puzzle
August 31, 2012
Order of evaluation of operands
September 3, 2012

Difference between struct and class in C++

In C++, a struct can have functions also, the way we have in a class. For example, the below definition of Node in C++ is perfectly valid.

struct Node
{
  private:
    int data;
    Node *link;
  public:
    // Default Constructor
    Node():data(0), link(NULL)
    {
        cout<< " Default Constructor";
    }
    // Single Argument Constructor
    Node(int d):data(d), link(NULL)
    {
        cout<< " Single Argument Constructor";
    }
};

What is the difference between the two ?

Answer:

struct in C++ are basically because of C language support in C++. Otherwise there is no real purpose of struct in Object Oriented Language like C++. What ever you want to do in a struct can be done in a class and vise-versa.

Having said that, following are the (only) two differences between a struct and a class:

1. Members of a struct are by default public

If no scope modifier (public / private / protected) is specified for any member of a class (data or function) then the member is by default private.

In a struct, the member is by default public.

For example: the below code (using struct) is fine.

struct ABC
{
    int data;
    void fun1()
    {
        cout<<"Hello Struct";
    }
};
int main()
{
    Node a;
    a.data = 10;   // Ok. data is public member
    a.fun1();      // Ok. fun1 is public
}

But if we use class, then it will be an error

class ABC
{
    int data;
    void fun1()
    {
        cout<<"Hello Class";
    }
};
int main()
{
    Node a;
    a.data = 10;   // ERROR. data is private
    a.fun1();      // ERROR. fun1 is private
}

2. default access specifier while inheritance in struct is public

If the Derived is a struct then the default access specifier is public. The below code

struct BaseStruct: BaseStructOrClass
{
    ...
}

is equivalent to

struct BaseStruct: public BaseStructOrClass
{
    ...
}

If nothing is specified in the Derived Class, then the default access specifier is private. Below Code

class BaseClass: BaseStructOrClass
{
    ...
}

is same as

class BaseClass: private BaseStructOrClass
{
    ...
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *