C++ – Class Versus Struct

cobject-oriented

In C++ and other influenced languages there is a construct called Structure (struct), and another called the class. Both are capable of holding functions and variables. Some differences are:

  1. Class is given memory in the heap and struct is given memory in the stack (remark: this is wrong for C++, but maybe correct in what the OP called "influenced languages")
  2. Class variable are private by default and in struct they are public

My question is: was the struct somehow abandoned for Class? If so, why? Other than the differences above, a struct can do all the same things that a class does. So why abandon it?

Best Answer

It is not abandoned at all. In fact, even modern languages like C# which make heavy use of class still offer you struct. As for when it's useful to choose one over the other, I refer you to this article:

Choosing Between Classes and Structures

Quoted from the MSDN article:

Consider defining a structure instead of a class if instances of the type are small and commonly short-lived or are commonly embedded in other objects.

Do not define a structure unless the type has all of the following characteristics:

  • It logically represents a single value, similar to primitive types (integer, double, and so on).
  • It has an instance size smaller than 16 bytes.
  • It is immutable.
  • It will not have to be boxed frequently.