How to Create virtual constructors and Destructors in C++2 min read

C++ allows programmers to create virtual destructors. But, it doesn’t allow virtual constructors to be created because of various reasons. To know why a virtual destructor is needed, consider the following program:

Output for the above program is as follows:

From the above output you can see that derived class destructor didn’t execute. This might lead to problems like memory leakage. To avoid such problems we make destructor in base class as virtual destructor.

Virtual destructor ensures that the derived class destructor is executed. To create a virtual destructor, precede the destructor definition with virtual keyword. Following program demonstrates a virtual destructor:

Output for the above program is as follows:

Now you can see that derived class constructor is also executed.

Advantages and Disadvantages of Inheritance

Advantages of inheritance are as follows:

  • Inheritance promotes reusability. When a class inherits or derives another class, it can access all the functionality of inherited class.
  • Reusability enhanced reliability. The base class code will be already tested and debugged.
  • As the existing code is reused, it leads to less development and maintenance costs.
  • Inheritance makes the sub classes follow a standard interface.
  • Inheritance helps to reduce code redundancy and supports code extensibility.
  • Inheritance facilitates creation of class libraries.

Disadvantages of inheritance are as follows:

  • Inherited functions work slower than normal function as there is indirection.
  • Improper use of inheritance may lead to wrong solutions.
  • Often, data members in the base class are left unused which may lead to memory wastage.
  • Inheritance increases the coupling between base class and derived class. A change in base class will affect all the child classes.

Take your time to comment on this article.

Leave a Comment