Need for Virtual Functions: When objects of different classes in a class hierarchy, react to the same message in their own ways, they are said to exhibit polymorphic behavior. Consider for an example
protected: int f_age;
public: Father(int n)
cout<<"Father's Age:"<< f_age;
class Son : public Father
Son(int n,int m):Father(n)
cout<<"Son's age:"<< s_age;
Father's Age: 45
Father's Age: 45
In C++, a function call can be bound to the actual function at runtime as well. This is known as runtime or late or dynamic binding. Runtime polymorphism allows postponing the decision of selecting the suitable member functions until runtime. This is achieved by using virtual functions. Virtual functions allow programmers to declare functions in a base class, which can be defined in each derived class. A pointer to an object of a base class can also point to the objects of its derived classes. In this case, a member function to be invoked depends on the class’s object to which the pointer is pointing to.
. . .
virtual returnType FunctionName(Arguments)
. . . .
. . .
Rules of Virtual Functions
- When a virtual function in a base class is created, there must be a definition of the virtual function in the base class even if the base class version of the function is never actually called.
- They cannot be static members.
- They can be a friend function to another class.
- They are accessed using object pointers. o A base pointer can serve as a pointer to a derived object since it is type compatible whereas a derived object pointer variable cannot serve as a pointer to base objects.
- Its prototype in the base class and the derived class must be identical for the virtual functions to work properly.
- The class cannot have virtual constructors but can contain virtual destructors.
- They should be declared in the public section of a class.
- Pure Virtual Functions: The pure virtual function is a virtual member function whose body is normally undefined. It is declared inside the class as virtual function prototype = 0; Derived classes must override the pure virtual functions of the base class
- Abstract Base Class: An abstract class is often defined as one that will be used to create any object (no data member, but virtual functions), but exist only to act as a base class of other classes. A class that has at least one pure virtual function is an abstract class.