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?
You can call a virtual function in a constructor, but be careful. It may not do what you expect. In a constructor, the virtual call mechanism is disabled because overriding from derived classes hasn't yet happened. Objects are constructed from the base up, “base before derived”.
Calling virtual functions in constructors makes your code extremely sensitive to the implementation details in derived classes. You can't control what derived classes do. Code that calls virtual functions in constructors is very brittle.
A class with one (or more) virtual pure functions is abstract, and it can't be used to create a new object, so it doesn't have a constructor.
Do not call pure virtual functions from constructor as it results in Undefined Behavior.
C++03 10.4/6 states
"Member functions can be called from a constructor (or destructor) of an abstract class; the effect of making a virtual call (10.3) to a pure virtual function directly or indirectly for the object being created (or destroyed) from such a constructor (or destructor) is undefined."
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With