why we should avoid virtual function calling in constructors or destructors in c++? In c++ calling a member function either in constructor or destructor is not recommended. If we call virtual function inside constructor or destructor then our c++ program would behave abnormal. Let us understand with a simple example.

Let us run the program and see output:

How it works

  • In the class Fruits the method taste() is a virtual function.
  • In the derived class Lemon the method taste() has been overridden.
  • Lemon class is derived class , so when we will create a Lemon object it’s parent class object would be created first and then derived class objects creation would happen through their respective constructors.
  • We have called function WhatisTaste() by Lemon object. lemon_obj.WhatisTaste();
  • When function WhatisTaset() invokes taste() function , it finds taste() function as virtual function and object is a Lemon object so it called taste() method overridden by Lemon class.
  • These invocation of methods happens through dynamic binding.

The above program is correct with no side effects. why we should avoid virtual function call inside constructor or destructor let us modify the program. Just call virtual function taste() from inside the constructor of Fruit class. See below code.

Let run the program and do think about the outputs.

From the output we can think why we should avoid virtual function calling in constructors or destructors. what is the problem with the output?

why we should avoid virtual function calling in constructors or destructors

In our program we have called WhatisTaste() method through polymorphic object lemon_obj even though it is giving output “Sweet”.  lemon_obj is a object of class Lemon. Lemon class has overridden the taste() function. So it is predicted that taste() invocation should always run overridden method version of taste() function.

So it is dangerous to call a member function of an object which is not constructed yet.

Ref:

https://msdn.microsoft.com/en-us/library/0y01k918.aspx




Related Contents to follow