C++: Can a struct inherit from a class?
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 didn't see in the C++ manual I studied with that a struct could inherit from another struct:
struct A {};
struct B : public A {};
I guess that in such a case, struct B inherits from all the data in stuct A. Can we declare public/private members in a struct?
But I noticed this:
class A {};
struct B : public A {};
From my online C++ manual:
A class is an expanded concept of a data structure: instead of holding only data, it can hold both data and functions.
Is the above inheritance valid even if class A has some member functions? What happen to the functions when a struct inherit them? And what about the reverse: a class inheriting from a struct?
Practically speaking, I have this:
struct user_messages {
std::list<std::string> messages;
};
And I used to iterate over it like this foreach message in user_messages.messages
.
If I want to add member functions to my struct, can I change its declaration and "promote" it to a class, add functions, and still iterate over my user_messages.messages as I did before?
Obviously, I am still a newbie and I am still unclear how structs and classes interact with each other, what's the practical difference between the two, and what the inheritance rules are...
Yes, struct can inherit from class in C++.
In C++, classes and struct are the same except for their default behaviour with regards to inheritance and access levels of members.
C++ class
- Default Inheritance = private
- Default Access Level for Member Variables and Functions = private
C++ struct
- Default Inheritance = public
- Default Access Level for Member Variables and Functions = public
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.