I am looking at the implementation of an API that I am using.
I noticed that a struct is inheriting from a class and I paused to ponder on it...
First, I d
In C++
struct A { /* some fields/methods ... */ };
is equivalent to:
class A { public: /* some fields/methods ... */ };
And
class A { /* some fields/methods ... */ };
is equivalent to:
struct A { private: /* some fields/methods ... */ };
That means that the members of a struct/class are by default public/private.
Using struct
also changes the default inheritance to public
, i.e.
struct A { }; // or: class A { };
class B : A { };
is equivalent to
struct A { }; // or: class A { };
struct B : private A { };
And the other way around, this
struct A { }; // or: class A { };
struct B : A { };
is equivalent to:
struct A { }; // or: class A { };
class B : public A { };
Summary: Yes, a struct
can inherit from a class. The difference between the class
and struct
keywords is just a change in the default private/public specifiers.
A class will not publicly inherit from a struct. A struct will publicly inherit from a class or a struct.
class A
{
public:
int a;
};
struct B : A
{};
B b; b.a=5; //OK. a is accessible
class A
{
public:
int a;
};
struct B : public A
{};
It means the same. B b; b.a=5; //OK. a is accessible
struct A
{int a;};
class B : A
{};
B b; b.a=5; //NOT OK. a is NOT accessible
struct A
{int a;};
class B : public A
{};
B b; b.a=5; //OK. a is accessible
Finally:
class A
{int a;};
class B : A
{};
B b; b.a=5; //NOT OK. a is NOT accessible
class A
{int a;};
class B : public A
{};
B b; b.a=5; //NOT OK. a is NOT accessible
Yes. Struct can inherit from a class and vice versa. The accessibility rule is
$11.2/2- "In the absence of an access-specifier for a base class, public is assumed when the derived class is declared struct and private is assumed when the class is declared class."
EDIT 2: So you can change your class as:. Note that it is a bad idea to have public data members usually.
class user_messages { // i also changed the name when OP was modified :)
public:
std::list<std::string> messages;
};