Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Initialization of inherited field

Tags:

I've a question about initialization of inherited members in constructor of derived class. Example code:

class A     { public:     int m_int;     };  class B: public A     { public:     B():m_int(0){}     }; 

This code gives me the following output:

In constructor 'B::B()': Line 10: error: class 'B' does not have any field named 'm_int'

(see http://codepad.org/tn1weFFP)

I'm guessing why this happens? m_int should be member of B, and parent class A should already be initialized when initialization of m_int in B happens (because parent constructors run before member initialization of inherited class). Where is a mistake in my reasoning? What is really happens in this code?

EDIT: I'm aware of other possibilities to initialize this member (base constructor or assignment in derived constructor), but I want to understand why is it illegal in the way I try it? Some specific C++ language feature or such? Please point me to a paragraph in C++ standard if possible.

like image 422
Haspemulator Avatar asked Oct 21 '10 04:10

Haspemulator


People also ask

How constructors are implemented when the classes are inherited?

When classes are inherited, the constructors are called in the same order as the classes are inherited. If we have a base class and one derived class that inherits this base class, then the base class constructor (whether default or parameterized) will be called first followed by the derived class constructor.

Does a derived class need a constructor C++?

In C++, a derived-class constructor always invokes a constructor for the base class. If an explicit invocation does not appear in the member-initializer list, there is an implicit call to the default constructor.

Why is base constructor called first?

This is why the constructor of base class is called first to initialize all the inherited members.

Do derived classes inherit constructors?

In inheritance, the derived class inherits all the members(fields, methods) of the base class, but derived class cannot inherit the constructor of the base class because constructors are not the members of the class.


1 Answers

You need to make a constructor for A (it can be protected so only B can call it) which initializes m_int just as you have, then you invoke :A(0) where you have :m_int(0)

You could also just set m_int = 0 in the body of B's constructor. It is accessible (as you describe) it's just not available in the special constructor syntax.

like image 178
Ben Jackson Avatar answered Sep 25 '22 05:09

Ben Jackson