Stack
Stack

Reputation: 235

constructors inherited in c++

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

Upvotes: 1

Views: 119

Answers (1)

OJFord
OJFord

Reputation: 11140

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.

Upvotes: 1

Related Questions