Calling pure virtual function in constructor gives

2019-02-23 16:32发布

问题:

This question already has an answer here:

  • call to pure virtual function from base class constructor 6 answers
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 it gives me error? The pure virtual foo is defined. What do I need to change in my code to make it work? I need pure virtual method from base class be called in its constructor.

回答1:

Calling virtual functions in a constructor is recognised as a bad thing to do.

During base class construction of a derived class object, the type of the object is that of the base class. Not only do virtual functions resolve to the base class, but the parts of the language using runtime type information (e.g., dynamic_cast (see Item 27) and typeid) treat the object as a base class type.

So your instantiation of b invokes the a constructor. That calls foo(), but it's the foo() on a that gets called. And that (of course) is undefined.



回答2:

Quoted from a book "Let Us C++"by Yashwant Kanetkar

It is always the member function of the current class , is called.That is , the virtual mechanism doesn't work within the constructor

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



回答3:

foo function is called in class a's constructor, and at that time, object b has not been fully constructed yet, hence it's foo implementation is unavailable.

Quoted from "Effective C++":

Don't call virtual functions during construction or destruction, because such calls will never go to a more derived class than that of the currently executing constructor or destructor