If we dont have virtual constructors then why we have virtual destructors? Can constructors also be virtual?
#include
using namespace std;
class base {
protected:
int a;
};
class derived : public base {
};
int main() {
base * pointer_of_base = new derived;
delete pointer_of_base; // this will delete the base calss not the derived
}
The constructors are called on one time when we create the object of the class so when we inherit the base class constructors calls only one time so no need to be virtual.
But when we accessing the derived class from the pointer of the base class, if we want to delete the object of derived class we delete it by the pointer of base class but delete(pointer_of_base) will call the destructor of the base class but the actual motto is to delete the derived class . thus we need the destructor be virtual in nature.