View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

Virtual Function in C++

Updated on 03/02/2025469 Views

During my experience with C++, I came across an interesting characteristic called the virtual function. This is a function that belongs to a base class and it is meant to be replaced in classes that inherit from this one. When you call a virtual function in C++ with a pointer or reference of the base class, C++ decides at runtime which version of the function to run. This dynamic linking is central to an important feature in C++ named polymorphism.

If you want to get better at software engineering and really know object-oriented programming, you should learn about virtual functions. You might find that courses on upGrad are very helpful for improving your abilities.

In this tutorial, I will walk you through virtual function in C++, and we will also look at the difference between virtual and pure virtual function in C++. We will also clarify some confusions around the concept of “c++ virtual class”. So, let’s begin!

Virtual and Pure Virtual Function in C++

In the C++ language, virtual functions represent a very strong feature known as polymorphism. To really value how useful and deep these virtual functions are, it is important to learn about both types: the normal virtual ones and those that are called pure virtual functions. These ideas make it possible to have adaptable and lively actions within intricate systems, which helps us create code that is easier to upkeep and build upon. We should explore each of these ideas further.

Virtual Function

A C++ virtual method or CPP virtual function is one that, when you put it in a parent class, can be changed by a child class. When this kind of function gets made in C++, the language creates a way to make sure that whenever you call this function for an object, even if you use different types of references or pointers to do so, the right version of the function is used. This behavior is what we refer to as dynamic binding or late binding.

Key Points about Virtual Functions:

  • Dynamic binding: When you call a function using a pointer or reference of the base class in C++, it decides which function to run at the time when the program is running. This is different from static binding, also known as early binding, where the decision about which function to call happens when compiling the code.
  • Virtual function table (vtable): In virtual function in C++, there is a special table called virtual function table, or vtable. It keeps track of the pointers that point to the virtual functions in a class. Every class comes with its own vtable and each object made from the class has a pointer pointing at this vtable for its own class. When you make a call to a virtual function, the right function is executed by using its specific pointer from the vtable.
  • Inheritance and override: A child class has the ability to change a virtual function from its parent class for certain uses. The parent class offers a general guideline, while the child classes add their own details.

Here's a refined example of how virtual in C++ work:

Example:

#include <iostream>
using namespace std;
class Base {
public:
// Virtual function
virtual void show() {
cout << "Base class" << endl;
}
};
class Derived : public Base {
public:
// Function is overridden
void show() override {
cout << "Derived class" << endl;
}
};
int main() {
Base *b; // Base class pointer
Derived d; // Derived class object
b = &d;

b->show(); // Prints "Derived class"

return 0;
}

Output:

Derived class

In this case, the display method in the foundational class called Base is set as virtual, and the class that inherits from it named Derived provides its own version of this method. The pointer 'b' which belongs to base type directs towards an object of Derived kind. When show is called, it executes Derived's version, showcasing polymorphism in action.

C++ Pure Virtual Function

A pure CPP virtual function is one that any actual, non-abstract subclass has to override. To declare it as such, you set the virtual function in the parent class equal to zero. This makes the base class abstract, meaning it cannot be instantiated directly.

Key Points about Pure Virtual Functions:

  • Abstract base class: This is a class that has minimum one function which is purely virtual. Such classes are for creating outlines in the form of interfaces, and then the subclasses fill out these outlines with concrete versions of those functions without any implementation yet.
  • Enforcing implementation: When the main class has a function that all the classes coming from it need to have, but no common version fits, we use abstract virtual functions. This makes an agreement for what these inheriting classes must do.

Here's a clear example illustrating pure virtual functions:

Example:

#include <iostream>
using namespace std;
class Shape {
public:
// Pure Virtual Function
virtual void draw() = 0;
virtual ~Shape() {}
};
class Circle : public Shape {
public:
void draw() override {
cout << "Drawing a circle." << endl;
}
};
class Rectangle : public Shape {
public:
void draw() override {
cout << "Drawing a rectangle." << endl;
}
};
void renderShape(Shape *shape) {
shape->draw();
}
int main() {
Circle c;
Rectangle r;
renderShape(&c); // Calls Circle's draw
renderShape(&r); // Calls Rectangle's draw
return 0;
}

Output:

Drawing a circle.
Drawing a rectangle.

In the above example:

  • The Shape class is abstract because it contains a pure virtual function draw().
  • Circle and Rectangle are both specific classes that come from the Shape class, and they each have their own way of doing the draw function.
  • The renderShape function receives a pointer for Shape and then it makes the draw method happen, showing that the right function gets called based on what type of object is really there.

To develop strong C++ applications, especially for systems whose operations are decided during runtime, it is very important to grasp these ideas. If you want to study further and use these ideas in actual situations, I suggest taking courses at upGrad where they offer detailed lessons on advanced topics related to software engineering and other important nuances from the world of C++ programming.

C++ Virtual Class

The phrase "virtual class" can be confusing because there are not actually virtual classes in C++. But generally, when someone says a C++ virtual class, they're talking about an abstract class. This kind of class contains at least one pure virtual function.

Abstract classes act like a template for other classes, allowing the creation of pointers or references to objects of the base class for enabling polymorphism. This concept is very important in C++, especially when you work with complicated system structures.

Virtual Function in C++ Example

To explain how virtual functions operate, I am going to demonstrate with an easy example. Imagine we have a main class called Shape and two subclasses named Circle and Rectangle.

Example:

#include <iostream>
using namespace std;
class Shape {
public:
// Virtual function
virtual void draw() {
cout << "Drawing a shape." << endl;
}
};
class Circle : public Shape {
public:
void draw() override { // Override Shape's draw()
cout << "Drawing a circle." << endl;
}
};
class Rectangle : public Shape {
public:
void draw() override { // Override Shape's draw()
cout << "Drawing a rectangle." << endl;
}
};
int main() {
Shape* s;
Circle c;
Rectangle r;
// Store the address of Circle
s = &c;
s->draw(); // Calls Circle's draw()
// Store the address of Rectangle
s = &r;
s->draw(); // Calls Rectangle's draw()
return 0;
}

Output:

Drawing a circle.
Drawing a rectangle.

This illustration makes it evident that virtual functions facilitate dynamic polymorphism. Through a pointer 's' from the base class, I am able to invoke the correct draw method based on whether the object is a Circle or Rectangle when the program runs.

In Conclusion

Virtual functions in C++ are very important because they allow polymorphism during the program run. This makes handling various object types and their actions simpler. Grasping the concepts of virtual and pure virtual functions is essential for those who want to become proficient in C++ or create advanced software systems.

To improve your understanding of virtual functions and better your programming abilities, think about joining classes at upGrad. There you can gain knowledge on complex C++ characteristics and the fundamentals of software engineering.

FAQs

1. What is a virtual function in C++?

In C++, a virtual function is one type of function in the main class. You write it with the word virtual, and you design it so that other classes coming from this main class can change its behavior. This lets the program choose which version of the function to run while it is running.

2. How do virtual functions enable polymorphism?

Virtual functions allow for different subclasses to respond to actions on objects from the parent class, making polymorphism possible. This results in dynamic linking or late binding, where the actual code that runs when a function is called gets decided while the program is running.

3. Why do we need virtual functions?

Virtual functions are very important for getting polymorphism during program execution. They enable us to call methods on objects of a derived class by using pointers or references from the base class, which makes our code adaptable and able to grow.

4. Can a constructor be virtual in C++?

No, in C++ constructors cannot be virtual. A constructor is a special kind of function that gets called when you make an object. It wouldn't be logical for it to be virtual because this type of function isn't something that can be inherited.

5. Can a virtual function have a different return type?

In C++, when you have a virtual function, the type it gives back needs to be identical or covariant, which applies for pointers or references that are connected with classes in both parent and child classes.

6. Can a virtual function be private in C++?

A virtual function is possible to be private in a base class. If another class derives from it, that new subclass can override this private function; however, the subclass cannot make a direct call to the function unless it has been given friend status by the base class.

7. What is the difference between virtual functions and pure virtual functions?

Virtual functions come with a basic setup which classes that inherit from them can change, but pure virtual functions have no setup and must be changed by any derived class that is not abstract.

8. What happens if we don't declare a virtual function as "override"?

If you do not declare a virtual function with override and the signatures are different from those in the base class, it becomes a new function in the subclass instead of an overriding one. This might cause small problems because of unexpected actions.

image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
advertise-arrow

Free Courses

Start Learning For Free

Explore Our Free Software Tutorials and Elevate your Career.

upGrad Learner Support

Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918045604032

Disclaimer

1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.

2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.