For working professionals
For fresh graduates
More
4. C++ Variable
10. C++ for Loop
12. C++ Lambda
13. Loop in C++
15. Array in C++
16. Strings in C++
17. Substring in C++
29. Vector in C++
30. Map in C++
31. Pair in C++
33. Iterators in C++
34. Queue in C++
36. Stack in C++
37. ifstream in C++
40. Templates in C++
43. Namespace in C++
46. Recursion in C++
48. C++ Shell
49. Setw in C++
51. Atoi in C++
54. C# vs C++
55. C++ GUI
56. C++ Game Code
57. Class in C++
58. C++ Header Files
63. Cin in C++
64. Printf in C++
65. Struct in C++
66. C++ List
68. C++ Comments
72. Sorting in C++
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!
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.
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.
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.
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.
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:
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.
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.
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.
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.
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.
Author
Start Learning For Free
Explore Our Free Software Tutorials and Elevate your Career.
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
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.