class Derived : public Base
{
public:
Derived() { a=0, foo(); }
virtual ~Derived();
virtual void foo() {printf("Derived::foo()");};
private:
int a;
};
The vtable is not an issue here. Before constructor is called, the vtable is already there. Now the problem is this:
Derived::Derived() will call Base::Base() first before entering the constructor body.
If Base::Base() calls a virtual function and the virtual function goes down to Derived.
But Derived's data is not intialized - the constructor is not finished. so a will be filled the garbagge. It will cause hidden problems.
So C++ standard says that if a class's constructor calls a virtual function, this function will not go down to derived. (i.e. vtable is not used).
It is a choice chosen by C++ standard. C++ compile will issue a warning generaly if a virtual method is called within constructor, but it is not prohibited.
{
public:
Derived() { a=0, foo(); }
virtual ~Derived();
virtual void foo() {printf("Derived::foo()");};
private:
int a;
};
The vtable is not an issue here. Before constructor is called, the vtable is already there. Now the problem is this:
Derived::Derived() will call Base::Base() first before entering the constructor body.
If Base::Base() calls a virtual function and the virtual function goes down to Derived.
But Derived's data is not intialized - the constructor is not finished. so a will be filled the garbagge. It will cause hidden problems.
So C++ standard says that if a class's constructor calls a virtual function, this function will not go down to derived. (i.e. vtable is not used).
It is a choice chosen by C++ standard. C++ compile will issue a warning generaly if a virtual method is called within constructor, but it is not prohibited.