• Register
110,660 points
12 7 5

The only difference between classand structis the visibility of its members, the members being structpublic by default while those of classare private by default.

Ignoring this difference, both constructs are the same:

Both can be used in inheritance

struct A {};
class B {};

struct C : public A, public B {};
class D : public A, public B {};

This implies that both can also have virtual functions, pure virtual functions, overwrite functions and use any level of inheritance.

Both can have public, protected and private members

struct S
{
     int public; // public member.
protected:
     protected int; // protected member.
private:
     private int; // private member.
};
class C
{
     private int; // private member.
protected:
     protected int; // protected member.
public:
     int public; // public member.
};

Both auto-generate the special functions

In both cases, if not explicitly defined, it will be created automatically:

  • Default constructor.
  • Copy constructor.
  • Motion builder.
  • Copy-allocation operator.
  • Destroyer.

Both can be pre-declared

struct S; // pre-declaration of S
class C; // pre-declaration of C

struct S {int i; }; // statement of S
class C {int i; }; // statement of C

I wanted to mention this point because it is possible to pre-declare an object as classand then declare it as struct(and vice versa); most compilers accept this although they usually show an alarm.

Both have the same structure in memory

A class and a structure with the same members in the same order will occupy the same memory and will have the same padding between members.

struct S {char c; short s; int i; float f; double d; };
class C {char c; short s; int i; float f; double d; };

static_assert (sizeof (S) == sizeof (C)); // True!
110,660 points
12 7 5