Reputation: 4328
What i know as of now that a constructor is called when an object is created. I also know that its not possible to create an object of an Abstract Class.
But when i run this piece of code i see the following :-
#include <iostream>
using namespace std;
class Pet {
public:
Pet(){cout<<"in base constructor\n";}
virtual ~Pet() = 0; //making pet abstract by making drstructor pure virtual
};
Pet::~Pet() {
cout << "~Pet()" << endl;
}
class Dog : public Pet {
public:
Dog(){cout<<"in drvd constructor\n";}
~Dog() {
cout << "~Dog()" << endl;
}
};
int main() {
Pet* p = new Dog; // Upcast
delete p; // Virtual destructor call
return 0;
}
When compiled and run its output is :-
in base constructor
in drvd constructor
~Dog()
~Pet()
why is constructor for Pet getting called even though its an abstract class and no object creation is allowed for it? So it boils down to finally is constructor called only in case of object creation?
Upvotes: 0
Views: 210
Reputation: 258578
its not possible to create an object of an Abstract Class
Don't take this ad-litteram. You can't create an object whose actual type is abstract.
But, if you implement that class (extend it and implement all pure virtual methods in it) and instantiate the new class, an object of the original abstract base class will be created as part of the new class.
Inheritance is a is-a
relationship. Dog
is a Pet
. When you create a Dog
, you create a Pet
. But you can't create a Pet
on its own.
Upvotes: 6
Reputation: 351
In your example, you can create a instance of Dog, but not Pet. i.e
Pet p; //Not possible, as destructor is abstract.
Dog d; //Allowed, because you derived from pet and ~pet( ) is defined.
The general sequence is if you create an object of a target class, the constructors are invoked in the order of base class -> child level -> ... -> target class. The destructors follow the reverse order.
To visualize this,think of target class is a superset of all its parent class/es. Here , Dog is a super set of Pet.
Upvotes: 1
Reputation: 477010
The correct statement is that "it is not possible to create a most-derived object of an abstract class". But objects can also be base-subobjects of more-derived objects, in which case they still need to be constructed.
(An object can be a subobject in three ways: A member subobject of a class-type object, a base subobject of a derived class-type object, or an element of an array.)
Upvotes: 2