Calling pure virtual function in constructor gives

2019-02-23 16:37发布

This question already has an answer here:

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.

3条回答
唯我独甜
2楼-- · 2019-02-23 17:08

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

查看更多
小情绪 Triste *
3楼-- · 2019-02-23 17:13

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

查看更多
冷血范
4楼-- · 2019-02-23 17:25

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.

查看更多
登录 后发表回答