Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling pure virtual function in constructor gives an error [duplicate]

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.

like image 272
user1873947 Avatar asked Dec 01 '22 20:12

user1873947


2 Answers

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.

like image 195
Brian Agnew Avatar answered Dec 10 '22 22:12

Brian Agnew


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

like image 27
Govind Balaji Avatar answered Dec 10 '22 23:12

Govind Balaji