Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 998
augustin Avatar asked Aug 26 '10 10:08

augustin


People also ask

Can structs have inheritance C?

No you cannot. C does not support the concept of inheritance.

Can struct derive from class C#?

A structure type can't inherit from other class or structure type and it can't be the base of a class. However, a structure type can implement interfaces. You can't declare a finalizer within a structure type.

Can struct can be used as a base class for another class?

A struct cannot inherit from another struct or class, and it cannot be the base of a class.


1 Answers

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
like image 120
Vite Falcon Avatar answered Oct 12 '22 23:10

Vite Falcon