Constructor and destructor inheritance

I believe that Constructors and Destructors in the base class cannot be inherited from derived classes base class. Do I understand correctly.

+5
c ++ inheritance base-class derived-class
Nov 12 '11 at 10:10
source share
5 answers

Your understanding is correct. For example, if you have

 class Base { Base(int i) {} }; class Derived: public Base {}; Derived d(3); 

This will not compile because the base constructor is not inherited. Please note that the default constructor and copies are created by the compiler, if possible, and call the corresponding constructor of the base classes, so for these constructors it looks as if they were inherited.

+4
Nov 12 '11 at 11:14
source share

I think this is what you are looking for? You can call the superclass constructor by adding the following to your class constructor

 SubClass(int foo, int bar) : SuperClass(foo) 

A complete example can be found here. What are the rules for calling the superclass constructor?

+1
Nov 12 '11 at 10:15
source share

In contrast, each constructor of a derived class calls the constructor of the base class [super-]. Each destructor of a derived class is called immediately before the destructor of the base class [super-].

Inheritance refers to classes, not functions or constructors.

0
Nov 12
source share

No, they are inherited. Destructors, for one, are always inherited and called in the reverse order of creation. For example, if we have the classes foo , bar and xyzzy :

 class foo { ... }; class bar : public foo { ... }; class xyzzy : public bar { ... }; 

Then, if you destroyed an object of class xyzzy , destructors will be called in the following order: ~xyzzy() , ~bar() and finally ~foo() .

Constructors are also always inherited, but they cannot be called directly. You must use them in the constructor initialization list or call the default constructor (the default constructor is one that takes no arguments). For example, let's say that we have the following classes:

 class foo { public: foo(); foo (int _value); } class bar : public foo { int m_value; public: bar (int _value); } bar::bar (int _value) { m_value = _value; } 

In this case, when creating an object of class bar , the constructor for foo is called, but this is the default constructor ( foo() ). A constructor that takes an argument foo (int _value) is never called. But if we change the constructor definition of bar (int _value) to this:

 bar::bar (int _value) : foo (256 - _value), m_value (_value) { } 

Then, instead of the default constructor, foo (int _value) will be called.

0
Nov 12
source share

As this question explains, constructors are not inherited. The same goes for destructors.

0
Nov 12 '11 at 11:11
source share



All Articles