1

Excerpt from here:

Constructors are different from other class methods in that they create new objects, whereas other methods are invoked by existing objects. This is one reason constructors aren’t inherited. Inheritance means a derived object can use a base-class method, but, in the case of constructors, the object doesn’t exist until after the constructor has done its work.

  1. Does a constructor create new object or when a object is called the constructor is called immediately?

  2. It is said that a constructor and destructor is not inherited from the base class to the derived class but is the program below a contradiction, we are creating an object of the derived class but it outputs constructor and destructor of the base class also?


class A{ public: A(){ cout<< Const A called<<endl; } ~A(){ cout<< Dest A called <<endl; } }; Class B : public A{ public: B(){ cout<< Const B called <<endl; } ~B(){ cout<< Dest B called <<endl; } }; int main(){ B obj; return 0; } 

Output:

Const A called

Const B called

Dest B called

Dest A called

3
  • 1
    Define a constructor with a parameter in A, then see if B has inherited a constructor with a parameter. Commented Apr 4, 2015 at 13:58
  • That is a very misleading post, based on a very misleading quote from a book that isn't held in very high regard as a source of C++ knowledge. You should simply ignore all of it. Derived classes inherit all members from their base. Commented Apr 4, 2015 at 13:59
  • C++11 and later support constructor inheritance, so the premise is incorrect. Commented Apr 4, 2015 at 14:39

1 Answer 1

1

A derived class D does not inherit a constructor from B in the sense that, specifying no explicit D constructors I can use my B(int) like to construct a new D(1);.

However, what I can do is use a base class constructor in the definition of a derived class constructor, like D::D(void) : B(1) {}.

Less abstract, suppose I have a constructor for Person that takes a gender parameter, I might wish to create a:

class Son: Person{ public: Son(void) : Person(male) {}; }; 

to construct a Son, which is obviously a Person, but certainly doesn't need parameterised gender.

Destructors are 'inherited' in the sense that on the closing brace of D::~D(){} a call to ~B() is implied.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.