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.
foo
function is called in classa
's constructor, and at that time, objectb
has not been fully constructed yet, hence it'sfoo
implementation is unavailable.Quoted from "Effective C++":
Quoted from a book "Let Us C++"by Yashwant Kanetkar
So, the
foo()
ofclass a
gets called. Since it is declaredpure virtual
, it will report an errorCalling virtual functions in a constructor is recognised as a bad thing to do.
So your instantiation of
b
invokes thea
constructor. That callsfoo()
, but it's thefoo()
ona
that gets called. And that (of course) is undefined.