When i invoke a virtual function from a base constructor, the compiler does not give any error. But when i invoke a pure-virtual function from the base class constructor, it gives compilation error.
Consider the sample program below:
#include <iostream>
using namespace std;
class base
{
public:
void virtual virtualfunc() = 0;
//void virtual virtualfunc();
base()
{
virtualfunc();
}
};
void base::virtualfunc()
{
cout << " pvf in base class\n";
}
class derived : public base
{
public:
void virtualfunc()
{
cout << "vf in derived class\n";
}
};
int main()
{
derived d;
base *bptr = &d;
bptr->virtualfunc();
return 0;
}
Here it is seen that the pure virtual function has a definition. I expected the pure virtual function defined in base class to be invoked when bptr->virtualfunc() is executed. Instead it gives the compilation error:
error: abstract virtual `virtual void base::virtualfunc()’ called
from constructor
What is the reason for this?
Do not call pure virtual functions from constructor as it results in Undefined Behavior.
C++03 10.4/6 states
You get an compilation error because you have not defined the pure virtual function
virtualfunc()in the Base class. To be able to call it, it must have an body.Anyways, calling pure virtual functions in constructors should be avoided as it is Undefined Behavior to do so.