Explain the purpose of the 'virtual' keyword and virtual functions in C++.
Explain the purpose of the virtual keyword and virtual functions in C++.
34104-Aug-2023
Updated on 06-Aug-2023
Aryan Kumar
06-Aug-2023The virtual keyword in C++ is used to declare a virtual function. A virtual function is a member function in a base class that can be redefined in a derived class. When you refer to a derived class object using a pointer or a reference to the base class, you can call a virtual function for that object and execute the derived class's version of the function.
Virtual functions are used to achieve polymorphism in C++. Polymorphism is the ability of an object to take on different forms. In the context of C++, polymorphism allows you to have a base class pointer that can point to objects of different derived classes. When you call a virtual function on a base class pointer, the compiler will determine the actual function to call at runtime, based on the type of the object that the pointer is pointing to.
For example, consider the following code:
C++
In this code, we have a base class called Animal, and two derived classes called Dog and Cat. The speak() function is declared as virtual in the Animal class. This means that it can be redefined in the derived classes.
In the main() function, we create a pointer to the Animal class. We then assign it to a Dog object and a Cat object. When we call the speak() function on the pointer, the compiler will determine the actual function to call at runtime, based on the type of the object that the pointer is pointing to.
In the first case, the pointer is pointing to a Dog object, so the Dog version of the speak() function will be called. In the second case, the pointer is pointing to a Cat object, so the Cat version of the speak() function will be called.
Virtual functions are a powerful tool that can be used to achieve polymorphism in C++. They allow you to have a base class pointer that can point to objects of different derived classes, and to call the correct function for each object at runtime.
Gulshan Negi
05-Aug-2023Well, in simple line In C++ programming language, virtual keyword is used in OOP (object-oriented programming) to declare and define the virtual functions.
Code Reference:
Thanks