How to use virtual functions in Polymorphism (C++)

How to use virtual functions in Polymorphism (C++)

Virtual Functions

We know that when a base class pointer refers to a derived class object, the extra features in derived class are not available. To access the extra features in the derived class, we make the functions in the base class as virtual. Syntax for creating a virtual function is as follows:
A class which contains one or more virtual functions is known as a polymorphic class. Following program demonstrates accessing derived class features using virtual functions:

Rules for Virtual Functions

Following points must be remembered while working with virtual functions:
  • Virtual functions must be members of a class.
  • Virtual functions must be created in public section so that objects can access them.
  • When virtual function is defined outside the class, virtual keyword is required only in the function declaration. Not necessary in the function definition.
  • Virtual functions cannot be static members.
  • Virtual functions must be accessed using a pointer to the object.
  • A virtual function cannot be declared as a friend of another class.
  • Virtual functions must be defined in the base class even though it does not have any significance.
  • The signature of virtual function in base class and derived class must be same.
  • A class must have a virtual destructor but it cannot have a virtual constructor.

Pure Virtual Functions

When the code for virtual function in a base class is insignificant, we can make such virtual functions as pure virtual functions. A pure virtual function is a virtual function without any definition. Syntax for creating a pure virtual functions is as follows:
virtual return-type function-name(params-list) = 0;
A class which contains at least one pure virtual function is called a abstract class and the class which provides the definition for the pure virtual function is called a concrete class.

Late Binding (Dynamic Polymorphism)

In inheritance when a derived class object is assigned to a base class pointer, and a polymorphic function is invoked, the function call is linked to the function definition at run-time. Such postponement of linkage to run-time instead of compile-time is called as late binding or dynamic polymorphism.’

Please Do not Spam, use a clear English that we can understand thank you.

Previous Post Next Post

Contact Form