C / C++ FAQs & Programming Resources - ProkutFAQ : ClassVsStruct

HomePage Recent Changes Recently Commented Login/Register
Quick Links
Categories
Links

What are the differences between struct and class?

There is not much difference between the keywords struct and class in C++.
The members of a struct are public by default, while in class, they are private. It is thus very important to specify the access specifiers instead of relying on the defaults. Default values often end up confusing programmers who end up managing code that you wrote.

As a simple example:
class point1
{
   int x; //private by default.
   public:
   int y;
   
};

struct point2
{
   int x; //public by default.
   public:
   int y;
};

int main()
{
   point1 a;
   point2 b;
   a.x = 0;  //error because x is private
   b.x = 0;  //Valid, as the member x is a public member by default in struct.
}

 Comments [Hide comments/form]
Your second explanation is incorrect, that's not the difference between structs and classes. The POD-structs are classes. You can use the keyword 'class' even for that. From the C++ standard:

4. A structure is a class defined with the class-key struct; its members and base classes (clause 10) are public by default (clause 11). A union is a class defined with the class-key union; its members are public by default and it holds only one data member at a time (9.5). [Note: aggregates of class type are described in 8.5.1. ] A POD-struct is an aggregate "class" that has no non-static data members of type non-POD-struct, non-POD-union (or array of such types) or reference, and has no user-defined copy assignment operator and no user-defined destructor. Similarly, a POD-union is an aggregate union that has no non-static data members of type non-POD-struct, non-POD-union (or array of such types) or reference, and has no userdefined copy assignment operator and no user-defined destructor. A POD class is a class that is either a POD-struct or a POD-union.

Zaman Bakshi
-- 220.224.87.140 (2007-04-07 17:15:09)
Another difference between struct and class is that the default inheritance is public and private respectively.

Regards,
Arvind Pai
-- 117.97.120.32 (2009-07-18 21:07:11)
Page was generated in 0.0347 seconds