What is the difference in C ++ between a structure and a class? According to what I understand, a structure is the way in c ++ to create an object, just as in python class is used.
What is the difference in C ++ between a structure and a class? According to what I understand, a structure is the way in c ++ to create an object, just as in python class is used.
The only difference between class
and struct
is the visibility of its members, being the members of struct
public by default while those of class
are private by default.
Obviating that difference, both constructs are the same:
struct A {};
class B {};
struct C : public A, public B {};
class D : public A, public B {};
This implies that both can also have pure virtual, virtual functions, overwrite functions and use any level of inheritance.
struct S
{
int publico; // miembro publico.
protected:
int protegido; // miembro protegido.
private:
int privado; // miembro privado.
};
class C
{
int privado; // miembro privado.
protected:
int protegido; // miembro protegido.
public:
int publico; // miembro publico.
};
In both cases, if it is not explicitly defined, it will be automatically created:
struct S; // pre-declaracion de S
class C; // pre-declaracion de C
struct S { int i; }; // declaracion de S
class C { int i; }; // declaracion de C
I wanted to mention this point because it is possible to pre-declare an object as class
and then declare it as struct
(and vice versa); Most compilers accept this although they usually show an alarm.
A class and a structure with the same members in the same order, will occupy the same in 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)); // Verdadero!
In C ++ struct
and class
are practically the same, with the only difference that in a struct
the default members are public and in a class
by default they are private.
A struct
may contain the same as a class
, methods, constructors, destructors, inheritance.
Apart from what is mentioned in other responses on the subject of visibility (topic that I will not comment on because it is already well documented in other responses) there is a second difference between the use of struct
and class
and is in the case of template
:
class
can be used to declare types for template
, while struct
no:
// ok
template<class T>
void func1(T t)
{ std::cout << t << '\n'; }
// ok
template<typename T>
void func2(T t)
{ std::cout << t << '\n'; }
// error
template<struct T>
void func3(T t)
{ std::cout << t << '\n'; }