C ++ Virtual Variable Method

Possible duplicate:
Calling virtual functions inside constructors

main.cpp

#include <iostream> class BaseClass { public: BaseClass() { init(); } virtual ~BaseClass() { deinit(); } virtual void init() { std::cout << "BaseClass::init()\n"; } virtual void deinit() { std::cout << "BaseClass::deinit()\n"; } }; class SubClass : public BaseClass { public: virtual void init() { std::cout << "SubClass::init()\n"; } virtual void deinit() { std::cout << "SubClass::deinit()\n"; } }; int main() { SubClass* cls = new SubClass; delete cls; return 0; } 

Why are init() and deinit() not correctly overridden, and are BaseClasses methods called instead of SubClasses? What are the requirements to make it work?

 BaseClass::init() BaseClass::deinit() 
+7
source share
2 answers

Because you are calling a virtual method inside the constructor. When building a base class, the derivative (SubClass) has not yet been built, so in fact it does not yet exist.

It is generally recommended that you avoid invoking virtual methods inside constructors.

+5
source

They are perfectly redefined.

But you called them from the base constructor, and when the base constructor is executed, the derived part of the object does not exist yet.

So, this is pretty much a security feature, and it's covered by the C ++ standard.

+5
source

All Articles