Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pure virtual invocation from constructor and destructor

The C++ standard says that invoking a pure virtual function from a constructor or destructor is forbidden. What is the reason for this? Why should the standard place a restriction like this?

like image 219
nitin_cherian Avatar asked Dec 28 '11 04:12

nitin_cherian


People also ask

Can you call a pure virtual function in a constructor?

Pure virtual functions must not be called from a C++ constructor. As a general rule, you should never call any kind of virtual function in a constructor or destructor because those calls will never go to a more derived class than the currently executing constructor or destructor.

Is it safe to call virtual methods in constructor and destructor?

Calling virtual functions from a constructor or destructor is considered dangerous most of the times and must be avoided whenever possible. All the C++ implementations need to call the version of the function defined at the level of the hierarchy in the current constructor and not further.

Can destructor be pure virtual?

Yes, it is possible to have a pure virtual destructor. Pure virtual destructors are legal in standard C++ and one of the most important things to remember is that if a class contains a pure virtual destructor, it must provide a function body for the pure virtual destructor.

Can we place virtual for constructor and destructor?

In C++, the constructor cannot be virtual, because when a constructor of a class is executed there is no virtual table in the memory, means no virtual pointer defined yet. So, the constructor should always be non-virtual. But virtual destructor is possible.


1 Answers

At the point a class destructor is run, all subclass destructors have already been run. It would not be valid to call a virtual method defined by a subclass, for which its destructor has already run.

A similar restriction exists around calling virtual methods in constructors. You can't call a virtual method for a subclass whose constructor has not yet run.

like image 65
Greg Hewgill Avatar answered Oct 20 '22 10:10

Greg Hewgill