C++: Can a struct inherit from a class?

augustin picture augustin · Aug 26, 2010 · Viewed 36.3k times · Source

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...

Answer

Vite Falcon picture Vite Falcon · Aug 26, 2010

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