InterviewSolution
| 1. |
What do you understand about virtual functions in the context of the C++ programming language? |
|
Answer» A virtual function is a MEMBER function defined in a base class that is redefined (overridden) by a derived class. When you use a pointer or a reference to the base class to refer to a derived class object, you can call a virtual function for that object and have it run the derived class's version of the function. Regardless of the type of reference (or pointer) used for the function call, virtual functions ENSURE that the right function is called for an object. They're mostly used to achieve polymorphism at runtime. The virtual KEYWORD is used to DECLARE functions in base classes. The call to a virtual function is resolved at runtime. Let us understand it better with the help of the following example: #include<bits/stdc++.h>using namespace std;class Parent {public: virtual void fun() // virtual function { cout << "Inside the fun() method of Parent class\n"; } void foo() { cout << "Inside the foo() method of Parent class\n"; }};class Child : public Parent {public: void fun() { cout << "Inside the fun() method of Child class\n"; } void foo() { cout << "Inside the foo() method of Child class\n"; }};int main(){ Parent *parent_object_pointer; Child child_object_pointer; parent_object_pointer = &child_object_pointer; // Virtual function, binded at runtime parent_object_pointer->fun(); // Non-virtual function, binded at compile time parent_object_pointer->foo(); return 0;}Output: Inside the fun() method of Child classInside the foo() method of Parent classExplanation: In the above code, the class Child inherits from the class Parent. Two methods fun() and foo() are defined in the Parent class and are overridden in the Child class. However, the fun() method is declared as a virtual function by using the ‘virtual’ keyword. Inside the main() method, we create an object of the Parent class and initialise it with an object of the Child class. So, the call to the fun() method is resolved at run time and not at compile time. Because of this, the statement “Inside the fun() method of Child class” gets printed. SIMILARLY, the call to the foo() method gets resolved at compile time and not at run time. Because of this, the statement “Inside the foo() method of Parent class” gets printed. |
|