Introduction of Polymorphism in C++

  • Polymorphism in C++ is one of the most important features of object-oriented programming.
  • Polymorphism is one of the four pillars of Object-Oriented Programming (OOP) in C++.
  • It simply means “one name multiple forms‟.
  • The word polymorphism consists of two Greek words – ‘poly’ means many/several, and ‘morphs’ means form/structure, which signifies the many uses of these operators and functions in different situations.

Definition of Polymorphism in C++

  • Polymorphism is an operation that may exhibit different behavior in different instances. The behavior depends upon the types of data used in the operation.
  • Polymorphism allows one interface to be used for multiple data types, making programs more flexible and scalable.
  • Polymorphism is a mechanism that allows implementing a function in different ways in different situations or environments.

Characteristics/Features of Polymorphism in C++

  • Polymorphism is the ability to use an operator or method/function in different ways.
  • Polymorphism refers to codes, operations, or objects that behave differently in different contexts.
  • Polymorphism gives different meanings to the operators or methods.
  • Polymorphism plays an important role in allowing objects with different internal structures to share the same external interface, i.e., a general class of operations may be accessed in the same manner even though specific actions associated with each operation may differ.
  • For polymorphism to occur, the following conditions must apply –
    • All different classes must be derived from a single base class.
    • The member function must be declared virtual in the base class. 

Examples of Polymorphism  

Suppose an expression

2 + 3           //This represents integer addition.
Again, the same + operator can be used with different meanings with strings such as :
 “Coders” + “helpline”        //This represents String addition.
Once again, the same + operator can also be used for floating point addition, such as :

2.321+5.021    //This represents floating point addition.

Thus, we saw from the above-given example that a single operator “+‟ behaves differently in different contexts, such as integer, string, or float, referring to the concept of polymorphism. The above polymorphism concept is said to be an operator overloading type. When the existing operator or function operates on a new data type more than once, it is said to be overloaded.

Types of Polymorphism

  • C++ shows two types of polymorphism – 

(i) Static Polymorphism/Compile-time Polymorphism/Early Binding or linking Polymorphism  and

(ii) Run-time Polymorphism/Dynamic Polymorphism/Late Binding/Linking Polymorphism.

  • Function overloading & operator overloading are examples of compile-time polymorphism, whereas run-time polymorphism can be achieved by the use of both derived classes/function overriding and virtual functions.
  • In polymorphism, a single function or an operator functioning in many ways depends upon the user to function properly.
Static/Compile-time/Early Binding Polymorphism
  • Compile-time polymorphism means the function to be executed is determined at compile time.
  • When the same operator (in operator overloading) and function (in function overloading) work differently on different arguments, producing different results.
  • In function overloading, the overloaded member functions are selected for invoking by matching arguments, in both data type and number of arguments. This information is known to the compiler in advance/at compile time, and, therefore, the compiler can select the appropriate function for a particular call at compile time itself. This is called early binding/static binding/static linking/compile-time polymorphism.
Run-time/Dynamic/Late Binding polymorphism.
  • Run-time polymorphism means the function to be executed is determined at runtime.
  • When the selection of the appropriate function in a program occurs dynamically at run time, it is called dynamic binding.
  • C++ supports run-time polymorphism by a mechanism called virtual functions. It exhibits late binding.
  • Dynamic Polymorphism only works when:
    • There is an inheritance.
    • A base class pointer is used.
    • The base class function is declared virtual with the same signature as the derived class.

    Benefits/Advantages of Polymorphism

    • Code Reusability: The main advantage of polymorphism is the creation of reusable code by the programmer – classes once written, tested, and implemented can be easily reused at other required places without caring about what’s written in the case.
    • By using polymorphic variables, memory is defined once, i.e., a single variable can be used to store multiple data types (integers, strings, etc.) rather than declaring a different variable again and again for each data format to be used.
    • Scalability: A polymorphic program can be easily extended, i.e., once an application is written using the concept of polymorphism, it can easily be extended, providing new objects that conform to the original interface. Also, it is unnecessary to recompile original programs again when a new type is added. Only re-linking is necessary to exhibit the new changes along with the old application. It is one of the greatest features of Oops.
    • It provides easier maintenance of applications.
    • It helps in achieving robustness in applications.

    Function Overriding

    • It is sometimes also called Method overriding.
    • Overriding is about the same method, and the same signature, but different classes connected through inheritance.
    • It is used to achieve runtime polymorphism, i.e., Function overriding is a type of polymorphism.
    • It enables us to provide a specific implementation of the function that is already provided by its base class.
    • Constructors are not normal methods, hence they cannot be overridden.
    • To occur Function override –
      • The function name must be the same in both the base and derived classes.
      • Function parameters also must be the same.
      • The function’s return type must also be the same.
      • Inheritance must exist.
      • Base class function must be virtual.
      • The call should be made using a base class pointer.

    Virtual Keyword

    • The word “virtual‟ means something that does not exist in reality, some sort of imaginary thing.
    • The virtual keyword in C++ is used to enable runtime polymorphism by ensuring that the function call is resolved at runtime based on the object being pointed to, not the pointer type.
    • When a base class function is declared as virtual, C++ decides which function to call at runtime, depending on the actual object, not on the type of pointer.
    • When to Use Virtual Keyword
      • When we want runtime polymorphism.
      • When a base class pointer points to derived class objects.
      • When functions are expected to be overridden.
    • Without the use of a virtual keyword
      • C++ uses compile-time binding (static binding).
      • The function call depends on the type of pointer.
    • With the use of a virtual keyword
      • C++ uses runtime binding (dynamic binding).
      • The function call depends on the type of object.
    • The virtual keyword is written only in the base class of Inheritance.
    • Function overriding must have the same signature and occur with the help of the Virtual keyword/function.
    • Constructors cannot be virtual.
    • Destructors are often declared virtual.

      Virtual Function

      • A virtual function is a class member function that is declared using the virtual keyword and supports runtime polymorphism by enabling dynamic function binding.
      • The concept of a virtual function is similar to a member function, but it does not physically exist, although it appears in the necessary places in a program.
      • It ensures runtime polymorphism, meaning the function call is resolved at runtime based on the type of object, not the pointer.
      • The functionality of virtual functions can be overridden in their derived classes.
      • When the form/nature of a member function of a class is changed at runtime. Such member functions are called virtual functions, and the corresponding class is called a Polymorphic class. The objects of the polymorphic class, addressed by pointers, change at runtime and respond differently to the same message.
      • Why is Virtual Function Needed?
        • Without virtual functions in the base class:
          • Function calls are resolved at compile time
          • Base class pointer always calls the base class function
        • With virtual functions in the base class:
          • Function calls are resolved at runtime
          • A base class pointer can call a derived class function
      • If a class has virtual functions, its destructor should be virtual.
      • Advantages
        • Virtual function supports runtime polymorphism.
        • It enables flexible and reusable code.
        • This concept is used in frameworks & interfaces.
        • It helps to achieve a dynamic behavior of the program.
      • Disadvantage
        • Virtual function has a slight performance overhead.
        • Virtual function uses slightly more memory due to the creation of the vtable by the compiler, which stores addresses of virtual functions, and the object contains a pointer to the vtable, which resolves function calls at runtime.

      Pure Virtual Functions

      • It is also called do-nothing functions/dummy functions.
      • The pure virtual function is always a virtual function.
      • A pure virtual function is a virtual function that has no definition or implementation in the base class
      • Derived classes must override it.
      • A pure virtual function is declared using = 0. 
      • Pure virtual functions are functions with a null body defined in the base class.
      • A pure virtual function makes the class abstract and forces derived classes to provide an implementation.
      • Syntax: To declare pure virtual functions –            
      class BaseClassName {
      public:
          virtual return_type function_name() = 0;
      };

      Here, the assignment operator is not used to assign zero to this function, but rather used to instruct the compiler that the function is pure.

      • Example

      virtual void display()=0;

      • Characteristics
        • Derived classes must override all pure virtual functions.
        • It is used to define interfaces.
        • It also supports runtime polymorphism.
        • Any normal function cannot be declared as a pure function.
        • A pure virtual function cannot be used for any operation.
        • It cannot be used to declare an object.
      • The need to use Pure Virtual Functions?
        • To force implementation in derived classes, i.e., this makes a derived class able to override them.
        • To achieve 100% abstraction
        • To define common behavior without implementation
        • To support plug-and-play architecture

        Abstract Class/Pure Abstract Class

        • A class in C++ containing at least one pure virtual function is referred to as an Abstract Class.
        • We cannot create, declare, or instantiate objects of an abstract class; i.e., any attempt to declare or create an object for an abstract class results in an error.
        • It is used as a base class and contains at least one pure virtual function.
        • The purpose of this class is to provide a common interface for derived classes.
        • A pointer of an abstract class can point to derived class objects.
        • The concept of an abstract class is used
          • To achieve/implement runtime polymorphism
          • Helps in code reusability.
          • To define rules/structure for child classes
          • To hide implementation details (abstraction)

          Demerits/Disadvantages of Polymorphism

          • Implementing polymorphism can be challenging for programmers in programming code.
          • Run-time polymorphism leads to performance issues because os with compilers manages all the related resources suddenly at run time.
          • Polymorphism reduces the readability of the program, i.e., identifying the runtime behavior of a program is difficult.
          Virtual Function Pure Virtual Function
          Has definition No definition
          Optional override Must override
          Class can be instantiated Class cannot be instantiated
          Partial abstraction Complete abstraction

          Loading

          Categories: C++

          0 Comments

          Leave a Reply

          Your email address will not be published. Required fields are marked *

          This site uses Akismet to reduce spam. Learn how your comment data is processed.