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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With