Virtual Function in C++ – Explore Benefits, Uses, & More
C++ is a general-purpose, object-oriented programming language developed in the early 1980s. It was designed to be an improved version of C, adding new features and capabilities that would allow developers to create more efficient software programs with fewer lines of code.
C++ is quite powerful than other popular languages due to its vast library, which contains numerous modules ranging from system utilities to graphical user interfaces (GUI). In this blog, we will understand what are virtual functions in C++, their features, advantages, and rules.
What are Virtual Functions in C++?
In C++, base classes can be overridden by derived classes. It allows the programmer to create objects. A virtual function is a member function with different behaviors but remains within the same type of hierarchy. To learn more about what is virtual function program in C++, you can pursue a full detail-oriented C++ programming course.
Virtual functions are declared using the “virtual” keyword and are defined in the header file of the base class. Let’s have a look at a basic C++ virtual function example.
Example of a Virtual Function in C++
Let’s have a look at a basic C++ virtual function example.
#include <iostream>
using namespace std;
class Subject {
public:
virtual void display() {
cout << "Subject Function" << endl;
}
};
class Science: public Subject {
public:
void display() {
cout << "Science Function" << endl;
}
};
int main() {
Science scienceObj;
// pointer of Subject type that points to scienceObj
Subject* subjectPtr = &scienceObj;
// calls the display () function of Science class
subjectPtr->display();
return 0;
}
Output:
Science Function
Explanation – The above code showcases polymorphism in C++. The Science class is inherited from the Subject class and overrides the display() function. In the main() function, an object of the Science class is created. A pointer of type Subject* is then designated as the address of the Science object. When subjectPtr->display() is called, it triggers the replace display() function of the Science class. Therefore, the output is a “Science Function”.
Also Read: Inline Function in C++
Features of Virtual Functions
Following are a few features of virtual functions.
- Virtual functions are resolved at runtime, which means that the compiler does not know which function to call until the program is running. This allows you to override the behavior of a function in a derived class.
- Derived classes can override virtual functions to change the behavior of existing objects without having to modify their original source code. This enables derived classes to provide their implementation of a function defined in the base class.
- It allows polymorphism, which means that the same interface can be used for different objects.
- Virtual functions help create abstract classes. Abstract classes are used to create a common interface for different classes.
- Virtual functions can be accessed through pointers or references of the base class.
Advantages of Virtual Function
A virtual function provides the following advantages.
- Virtual functions provide the ability to create flexible and extensible code.
- Developers can add or remove features from existing objects, reducing maintenance costs and improving overall flexibility by overriding a virtual function.
- It allows late binding, also known as run-time polymorphism.
- It can draw multiple shapes (e.g., circles, squares) on screen and treat them uniformly at the same time by invoking their draw() methods via a single call-like shape->draw(). Without virtual functions, it would require extra work for each shape type since the compiler wouldn’t know which version of draw() should be called at compile time. Therefore, you need separate calls like circle->draw(), rectangle->draw(), etc.
Limitations of Virtual Functions
Some of the limitations of virtual functions are as follows:
- They are difficult to debug in a complex system because virtual functions make it challenging to identify where the function is being called from.
- The function call slows down due to virtual mechanisms and makes it difficult for the compiler to optimize because it does not know the location of the function at compile time.
- Virtual functions store virtual function tables for each class. This adds additional memory overhead and increases the program’s memory footprint.
- Virtual function calls cannot be in-lined because they are resolved at runtime through the vtable.
- Virtual functions make the code more complex, making it difficult to understand the flow of the program.
Rules of Virtual Function
Following are some rules related to virtual functions. Let’s have a look.
- Virtual functions are not limited to being only members of base classes; they can also be declared as friends of a base class. This allows the friend function to access private and protected data members of the base class while still allowing derived classes to override it.
- Virtual functions must have identical return types and parameters in each derived class. This ensures that any call made through a pointer or reference to a particular object will always invoke the same method regardless of which type is stored there.
- Virtual functions cannot be static because static methods belong solely to their declaring type and are not inherited by derived classes; thus, overriding them wouldn’t make sense since no new implementation would exist for those derived types.
Pure Virtual Function in C++
A pure virtual function is an abstract method without any implementation. Its declaration includes only its signature (i.e., return type and parameters) along with a trailing ‘=0’ at the end. It must be implemented by all derived classes, otherwise, those classes will become abstract. This technique enables multiple inheritances, allowing more flexibility when designing object hierarchies and code reuse among related types.
Here is an example of a pure virtual function:
#include <iostream>
using namespace std;
// Abstract base class
class Shape {
public:
// Pure virtual function
virtual void draw() = 0;
};
class Circle : public Shape {
public:
void draw() override {
cout << "Drawing Circle" << endl;
}
};
class Rectangle : public Shape {
public:
void draw() override {
cout << "Drawing Rectangle" << endl;
}
};
int main() {
// Shape shape; // This would be an error, cannot instantiate Shape
Circle circle;
Rectangle rectangle;
// Pointers to Shape
Shape* shape1 = &circle;
Shape* shape2 = &rectangle;
// Polymorphic calls
shape1->draw(); // Outputs: Drawing Circle
shape2->draw(); // Outputs: Drawing Rectangle
return 0;
}
In this example, ‘Shape’ is an abstract base class with a pure virtual function ‘draw()’. The ‘Circle’ and ‘Rectangle’ are derived classes that override the draw() function. The statement virtual void draw() = 0; declares draw() as a pure virtual function. The ‘= 0’ syntax indicates that the function has no implementation in the ‘Shape’ class and must be overridden in any derived class that is not abstract.
The following is the output for the program:
Drawing Circle
Drawing Rectangle
Conclusion
Virtual function in C++ is useful tools for creating flexible and extensible code. By making use of these features, code can easily remain maintainable even when new functionality needs to be added over time, providing flexibility through overriding those specific implementations, if necessary.
Have you ever implemented virtual functions in your C++ program? Share an error that you encountered in the comments section below. To brush up on the fundamental C++ concepts before an interview, check out these top C++ interview questions.
FAQs
A virtual function allows referencing a derived class object using a pointer or a reference and executing its method.
A virtual function is a member function declared within the base class and overridden by the derived class. C++ uses late binding known as virtual tables. The virtual table resolves dynamic/late binding function calls.
The virtual pointer size on a 32-bit platform is 4 bytes, while it is 8 bytes on a 64-bit platform.
A virtual function is a function in the base class that can be overridden in derived classes. On the other hand, function overriding is the process where a derived class provides a specific implementation of a virtual function from the base class.
Virtual functions cannot be static because they rely on specific objects or references of the base class to determine which implementation of the function is called. This is not the case in static functions that rely on the class directly.
A virtual function is used to ensure that the correct function is called for an object regardless of the type of reference used for the function call. They also allow methods of derived classes to be called via references or pointers to the base class.
Void is a return type for functions that imply the function does not return any value. Virtual void denotes a class method that does not return a value and can be overridden in derived classes. It is used to enable polymorphic behavior in class hierarchies.