VOOZH about

URL: https://www.geeksforgeeks.org/cpp/how-to-create-virtual-function-in-cpp/

⇱ How to Create a Virtual Function in C++? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to Create a Virtual Function in C++?

Last Updated : 23 Jul, 2025

In C++, a virtual function is a member function that is declared in a base class and redefined in a derived class. It enables runtime polymorphism in our program. In this article, we will learn how to create a virtual function in C++.

Creating a Virtual Function in C++

We can use the virtual keyword to declare a function as virtual in the base class which is then overridden in a derived class.

Syntax to Declare a Virtual Function

The syntax for declaring a virtual function within the parent class is as follows:

virtual ReturnType FunctionName(Parameters){
// some body statements
};

We can then redefine this function in the derived class.

C++ Program to Create a Virtual Function

The below example demonstrates how we can create a virtual function using a virtual keyword in C++.


Output
Drawing a circle.

Time Complexity: O(1)
Space Complexity: O(1)

Note: We can also declare the function as pure virtual function by using the syntax: virtual func() = 0;


Comment