If we dont have virtual constructors then why we have virtual destructors? Can constructors also be virtual?
-
possible duplicate of [Why do we not have a virtual constructor in C++?](http://stackoverflow.com/questions/733360/why-do-we-not-have-a-virtual-constructor-in-c) – Tomasz Nurkiewicz Mar 29 '12 at 10:58
-
1@TomaszNurkiewicz: I think the question is rather, why do we have virtual destructors in C++? – Fred Foo Mar 29 '12 at 11:01
3 Answers
- There is no point in virtual constructor - you declare exactly what type is created, and it is well known in compile time. The compiler do not need [and actually cannot, since the dynamic dispatch is based on information which is created only after the object was created]. So there are no virtual constructors.
- Virtual destructors are important to prevent memory leaks, and
monitor the system. Assume you have
A* a = new B;
[B
inherits fromA
], and you laterdelete a;
- the compiler has no way of knowinga
is aB
[in the general case], and will invokeA
's destructor - if it wasn't virtual, and you might get a memory leak, or other faults. - Using virtual destructor - you ensure that
B
's destructor is invoked, since aB
object is being destroyed.

- 175,853
- 27
- 231
- 333
-
2
-
2@jhamb: When you invoke a constructor - it is something like `new MyClass;`. The *dynamic type* and the *static type* of the created object - are exactly the same, the real concrete object. – amit Sep 19 '12 at 19:53
Virtual destructors are needed because at destruction time, you don't always know what type you're dealing with:
Base *make_me_an_object()
{
if (the_moon_is_full())
return new Derived();
else
return new Base();
}
int main()
{
Base *p = make_me_an_object();
delete p;
}
The delete
in the above program's main
doesn't know whether its p
points to a Base
or a Derived
object, but if the Base
destructor is virtual
(as it should be), then delete
can use *p
's vtable to find the right destructor.
By contrast, at construction time, you always know what kind of object you're creating. (And in case you don't, then you can create a factory or "virtual constructor" that does know.)

- 355,277
- 75
- 744
- 836
#include<iostream>
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.

- 9,564
- 146
- 81
- 122

- 137
- 1
- 6