![]() |
VOOZH | about |
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++.
We can use the virtual keyword to declare a function as virtual in the base class which is then overridden in a derived class.
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.
The below example demonstrates how we can create a virtual function using a virtual keyword in C++.
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;