VOOZH about

URL: https://www.geeksforgeeks.org/cpp/behavior-of-virtual-function-in-the-derived-class-from-the-base-class-and-abstract-class/

⇱ Behavior of virtual function in the derived class from the base class and abstract class - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Behavior of virtual function in the derived class from the base class and abstract class

Last Updated : 23 Jul, 2025

In this article, we will discuss the behavior of Virtual Function in the derived class and derived class from the Abstract Base Class in C++.

Consider the following program:


Output
Inside Base

Explanation: When a pointer of the Base Class is declared pointing to an object of the Derived Class, then only declare the function as virtual in the base when it is needed to override it in the derived class. If the function is declared as a virtual in the Base Class, then it is not recommended to override it in the derived class, it will still call the virtual function and execute it.

The virtual keyword only works when going for runtime polymorphism and overriding the function of the base class in the derived class. If a virtual keyword is used, and it is not recommended to override that function in the derived class, then the virtual keyword is of no use. This property doesn't hold true for the Abstract Base class because there is no function body in the Base class as well. Below is the program to illustrate the same:

Program 1:


Output
Inside Derived

Program 2:

Output:

👁 Image

Explanation: If the above two programs are compared, we observe different behaviors based on whether or not the derived class overrides the pure virtual function print() from the base class.

In Program 1, the derived class overrides the pure virtual function print(). This works correctly because the derived class provides an implementation for the pure virtual function. Therefore, when b2->print() is called, it correctly calls the derived class's implementation.

In Program 2, however, the derived class does not override the pure virtual function print(). Since the pure virtual function is not implemented in the derived class, the derived class itself remains abstract. Consequently, attempting to instantiate an object of the derived class and calling b2->print() results in a compilation error because the function is not defined, and the derived class cannot be instantiated.

Comment