nitin_cherian
nitin_cherian

Reputation: 6655

Constructor and Destructor Inheritance

I believe Constructors and Destructors in base class cannot be inherited by derived classes of the base class. Is my understanding correct.

Upvotes: 8

Views: 11441

Answers (5)

celtschk
celtschk

Reputation: 19721

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. Note that default and copy constructor are created by the compiler if possible, and call the corresponding constructor of base classes, therefore for those constructors it looks as if those were inherited.

Upvotes: 5

Björn Pollex
Björn Pollex

Reputation: 76828

As this question explains, constructors are not inherited. The same applies to destructors.

Upvotes: 0

Septagram
Septagram

Reputation: 9785

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

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

Then if you destoy 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 have to use them in the constructor initialization list or the default constructor will be called (default constructor is the one that takes no arguments).For example, say we have 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 you create an object of class bar, a constructor for foo is invoked, but it's the default constructor (foo()). Constructor that takes an argument foo (int _value) is never called. But if we changed definition of the bar (int _value) constructor to this:

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

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

Upvotes: 0

On the contrary, each constructor of a derived class calls a constructor of the base [super-] class. Each destructor of a derived class is called just before the destructor of the base [super-] class.

Inheritance concerns classes, not functions or constructors.

Upvotes: 0

Niels
Niels

Reputation: 49929

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 full example can be found here What are the rules for calling the superclass constructor?

Upvotes: 1

Related Questions