Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invoking virtual function and pure-virtual function from a constructor

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?

like image 457
nitin_cherian Avatar asked Dec 27 '11 07:12

nitin_cherian


People also ask

Can a constructor be a virtual function?

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”.

Why is it not acceptable to call a virtual method from the constructor of an abstract class?

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.

Can a pure virtual class have a constructor?

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.


1 Answers

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.

like image 70
Alok Save Avatar answered Nov 15 '22 02:11

Alok Save