Constructor and Destructor Inheritance

10,506

Solution 1

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.

Solution 2

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?

Share:
10,506
nitin_cherian
Author by

nitin_cherian

nitin_cherian: Sneior Lead Engineer at ADVA Optical Networking, Bangalore, India Languages worked on: C, C++, Python Operating systems worked on: Linux Current Interests: Python Language, Game development in Python. Crafting Quality code in Python. Online Courses: Cryptography1, Interactive Programming in Python @ www.coursera.com. Hobbies: Reading short articles in newspaper and magazines.

Updated on June 09, 2022

Comments

  • nitin_cherian
    nitin_cherian about 2 years

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