Virtual functions in C++
Virtual functions
Virtual functions are special type of member functions (MFs) which are defined in base class and are redefined in derived classes. Virtual functions perform specific tasks of simplifying function calls and act as a vehicle for induction of polymorphism in OOP. A virtual function is declared by placing the keyword virtual before the declaration of member function in the base class. The keyword virtual needs to be used for defining virtual function in the base class.
When a virtual function is called through a pointer to a base class, the derived class function is activated. Virtual function although defined in base class, does not perform any function except to act as a reference point or placeholder for its redefinition in derived class.
Making calls on virtual functions
For making calls on virtual functions, the following mechanism is used in main():
- A pointer to base class is defined. Ex: ob1 *ptr; here ob1 is base class object.
- Objects for different classes are created. Example,
class XXX ob1;
class YYY ob2; - The address of the object is placed in the base class pointer as:
ptr1 = &ob1;
ptr2 = &ob2; - Pointer is used to call the virtual function as:
ptr->f() - These steps have to be followed for each object
Example: class parent { int x, y; public: virtual void display(); int sum(); } class child: public parent { int x, y; public: virtual display(); //no need to put virtual here, but it’s a virtual function. actual function implementation is found here. int sum(); } int main() { parent *ptr; child ob; ptr = &ob; ptr -> display() // runtime binding ptr -> sum(); //compile time binding return 0; } Points
- A virtual function is one that doesn’t really exist but it appears real in some parts of a program
- Polymorphic features are incorporated using the virtual functions
- Virtual keyword differentiates virtual function from conventional function declaration
- An object of a class must be declared either as a pointer to class or reference to a class
Run the following program to understand concept of VIRTUAL FUNCTION in C++.
Some points on virtual functions:
- Only a MF of a class can be declared as virtual.
- The use of virtual in the function definition is invalid i.e., keyword virtual should not be repeated in the definition if the definition occurs outside the class declaration.
- Virtual function can’t be static. Because virtual member is always a member of a particular object in a class rather than a member of the class.
- It is an error to make a constructor as virtual. i.e., a virtual function can’t have a constructor member function (MF). But it can have a destructor member function. Note that destructor member function can be virtual even though it does not take any arguments.
- It is an error to redefine a virtual function with a change of return data type in the derived class with same arguments as those of virtual function in the base class.