Friday, June 8, 2012

Difference between class and struct in cpp

1) Members of a class are private by default and members of struct are public by default. For example program 1 fails in compilation and program 2 works fine.

// Program 1 to show we can't access the class data directly
#include <iostream>
using namespace std;

class Demo 

{
    int x;         // x is private (by default)
};

int main()
{
   Demo d;
   d.x = 20;      // compiler error because x is private
   cout << d.x ;
}

// Program 2 to show we can access struct data directly
#include <iostream>
using namespace std;

struct Demo
{
    int x;       // x is public (by default)
};

int main()
{
  Demo d;
  d.x = 20;    // works fine because x is public
  cout << d.x ;
}


2) When deriving a struct from a class/struct, default access-specifier for a base class/struct is public. And when deriving a class, default access specifier is private. For example program 3 fails in compilation and program 4 works fine.

// Program 3 to show inheritance between classes is, private by-default
#include <iostream>
using namespace std;

class Base

{
   public:
      int x;
};

class Derived : Base { };  
  // is equilalent to class Derived : private Base {}

int main()
{
  Derived d;
  d.x = 20;        // compiler error becuase inheritance is private
  cout << d.x ;
}

// Program 4 to show inheritance between structure is, public by-default
#include <iostream>
using namespace std;

struct Base 

{
    public:
       int x;
};

struct Derived : Base { };   // is equilalent to struct Derived : public Base {}

int main()
{
   Derived d;
   d.x = 20;       // works fine becuase inheritance is public
   cout << d.x ;
}


Note: struct in c# doesn't  support inheritance.

No comments:

Post a Comment