Open In App

How to Create a Virtual Function in C++?

Last Updated : 22 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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++




// C++ Program to create a Virtual function
#include <iostream>
using namespace std;
  
// Base class
class Shape {
public:
    // Virtual function
    virtual void draw()
    {
        cout << "Drawing a shape." << endl;
    }
};
  
// Derived class
class Circle : public Shape {
public:
    // Override the virtual function
    void draw() override
    {
        cout << "Drawing a circle." << endl;
    }
};
  
int main()
{
  
    // Create objects
    Shape* shapeptr;
    Circle circle;
    shapeptr = &circle;
  
    // Virtual function, binded at runtime
    shapeptr->draw();
  
    return 0;
}


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;


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads