C++ Blog

Tuesday, March 06, 2007

Difference between C struct and C union

C struct variable size is equal to the sum of the sizes of all the members in it. But C union variable size is euqal to the largest size of the member in it. In other words, union uses one large block equivalent to the largest member and share this memory for all the members, but struct has memory allocated for each of its members.

Difference between C struct and C++ struct

C struct can have only members, it can't have methods or access specifiers. It can't inherit a structure.
C++ struct can have members, methods and has access specifiers to restrict its access. It can inherit other structures also.

Difference between C++ struct and class

The only difference between C++ struct and class is, the members of a struct are "public" by default but in class it is "private"

Difference between C++ union and class

Difference between C++ union and class is, the members of a union are "public" by default but in class it is "private".
C++ union can have constructor, destructor but not virtual functions. They can't have virtual functions because unions can't act as a base class. Unions can't have base class also. Unions can't have static members. An object of a class with a constructor or a destructor or a user-defined assignment operator can't be a member of union.