Click here to Skip to main content
15,895,841 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
why structure is replaced by class in c++. If only difference between structure and class is default public and private identifier then why class is being introduced. Can any help me understanding the exact difference between these? Thanks in advance.

What I have tried:

I searched my sites but every place only difference of public and private identifier is given.
Posted
Updated 9-Mar-16 22:58pm

Essentially that is the only difference, but it's important to understand what the implications of that distinction is. C++ was designed to support object-orientation which means that it should, from the ground up, emphasise features such as data hiding and encapsulation. To that end, you want to hide as much as possible in a class, only exposing well-defined, meaningful operations. So, the class is private by default. However, C++ also has backwards compatibility with C which means that it has to be able to interact with C structures which were not designed to be object-oriented.
 
Share this answer
 
As I pointed out in my comment to AwildaHarrison's answer, the ONLY difference between structs and classes, in C++ programming language, is their default access specifiers: struct default access is public, while class one is private. That means you might write a class and a struct with identical properties, try, for instance:
(basically, as Pete already noted, structs are redundant in C++)

C++
#include <iostream>
using namespace std;

struct A
{
  A(){cout << "A()" << endl; }
  ~A(){cout << "~A()" << endl;}
};

class B
{
public:
  B(){cout << "B()" << endl; }
  ~B(){cout << "~B()" << endl;}
};

int main()
{

  A a;
  B b;

  cout << "sizeof(A) " << sizeof(A) << endl;
  cout << "sizeof(B) " << sizeof(B) << endl;
}
 
Share this answer
 
Comments
[no name] 11-Mar-16 12:17pm    
+5
This will make some cringe, but I like using "struct" instead of class since I start out with the public members at the top. I keep the private stuff down towards the end. When you first open a header file, you see all the public members right away.

The word "class" was added to C++ only to make some programmers feel, well, "classy".
CPallini 11-Mar-16 12:51pm    
LOL!
Thank you.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900