本文发表在 rolia.net 枫下论坛Both the vtable and vptr are created in compile time and already within the binary image file. Constructor does NOTHING with filling up vtable slots and asigning vptr.
Now I am curious that it will be NOT a big issue for compiler to resolve this problem at compile time. In general, is it make sence that calling virtual member function within the member function can be resolved at compile time? For example,
class Base
{
public:
Base();
virtual ~Base();
virtual void foo(){printf("Base::foo()");};
virtual void bar(){printf("Base::bar()"); foo();};
};
class Derived : public Base
{
public:
Derived();
virtual ~Derived();
virtual void foo() {printf("Derived::foo()");};
virtual void bar() {printf("Derived::bar()"); foo();}
};
For outside Derived class,
void test(Base* pB)
{
pB->bar(); // calling Base::bar() or Derived::bar() has to be resolved at runtime
}
However inside Base::bar() member function's body, calling foo() can be resolved at compile time as *this->vptr[2](this); (assume vptr[0] for RTTI and vptr[1] for virtual destructor). Same apply to Derived::bar() member function body for calling foo().
For the same reason, as apply to special case, calling virtual function inside constructor also can be resolved at compile time. Thus what's the issue is?
Just for testing, I play with MSVC and there is no problem.
Do you guys have any specific scnario for calling virtual function inside constructor fails?更多精彩文章及讨论,请光临枫下论坛 rolia.net
Now I am curious that it will be NOT a big issue for compiler to resolve this problem at compile time. In general, is it make sence that calling virtual member function within the member function can be resolved at compile time? For example,
class Base
{
public:
Base();
virtual ~Base();
virtual void foo(){printf("Base::foo()");};
virtual void bar(){printf("Base::bar()"); foo();};
};
class Derived : public Base
{
public:
Derived();
virtual ~Derived();
virtual void foo() {printf("Derived::foo()");};
virtual void bar() {printf("Derived::bar()"); foo();}
};
For outside Derived class,
void test(Base* pB)
{
pB->bar(); // calling Base::bar() or Derived::bar() has to be resolved at runtime
}
However inside Base::bar() member function's body, calling foo() can be resolved at compile time as *this->vptr[2](this); (assume vptr[0] for RTTI and vptr[1] for virtual destructor). Same apply to Derived::bar() member function body for calling foo().
For the same reason, as apply to special case, calling virtual function inside constructor also can be resolved at compile time. Thus what's the issue is?
Just for testing, I play with MSVC and there is no problem.
Do you guys have any specific scnario for calling virtual function inside constructor fails?更多精彩文章及讨论,请光临枫下论坛 rolia.net