How to Create a Virtual Function in C++?
Last Updated :
22 Feb, 2024
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++.
C++
#include <iostream>
using namespace std;
class Shape {
public :
virtual void draw()
{
cout << "Drawing a shape." << endl;
}
};
class Circle : public Shape {
public :
void draw() override
{
cout << "Drawing a circle." << endl;
}
};
int main()
{
Shape* shapeptr;
Circle circle;
shapeptr = &circle;
shapeptr->draw();
return 0;
}
|
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;
Share your thoughts in the comments
Please Login to comment...