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?
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-arelationship.Dogis aPet. When you create aDog, you create aPet. But you can’t create aPeton its own.