Calling a pure virtual function in the constructor gives an error

class a //my base class { public: a() { foo(); } virtual void foo() = 0; }; class b : public a { public: void foo() { } }; int main() { b obj; //ERROR: undefined reference to a::foo() } 

Why does this give me an error? A pure virtual foo is defined. What do I need to change in my code for it to work? I need a pure virtual method from the base class, which is called in its constructor.

+4
source share
3 answers

Calling virtual functions in the constructor is recognized as a bad thing .

When constructing the base class of an object of a derived class, the type of the object is the base class. Not only virtual functions allow the base class, but parts of the language that use runtime (for example, dynamic_cast (see clause 27) and typeid) process the object as a type of the base class.

So your instance of b calls the constructor of a . This calls foo() , but calls foo() on a . And this is (of course) undefined.

+13
source

Quoted from the book "Let Us C ++" by Yashvant Kanatelek

It is always a member function of the current class. This virtual mechanism does not work inside the constructor.

So, it calls foo() of class a . Since it is declared pure virtual , it will report an error

+2
source
Function

foo is called in the constructor of class a , and at that time the object b was not yet completely constructed, so the implementation of foo not available.

Quote from "Effective C ++":

Do not call virtual functions during construction or demolition, because such calls will never go to a more derived class than the currently executing constructor or destructor

+1
source

All Articles