Skip to main content

C++ Polymorphism

C++ Polymorphism

The term "Polymorphism" is the combination of "poly" + "morphs" which means many forms. It is a greek word. In object-oriented programming, we use 3 main concepts: inheritance, encapsulation, and polymorphism.

Real Life Example Of Polymorphism

Let's consider a real-life example of polymorphism. A lady behaves like a teacher in a classroom, mother or daughter in a home and customer in a market. Here, a single person is behaving differently according to the situations.

There are two types of polymorphism in C++:

C++
  • Compile time polymorphism: The overloaded functions are invoked by matching the type and number of arguments. This information is available at the compile time and, therefore, compiler selects the appropriate function at the compile time. It is achieved by function overloading and operator overloading which is also known as static binding or early binding. Now, let's consider the case where function name and prototype is same.
  1.    class A                                  //  base class declaration.  
  2.   {  
  3.        int a;  
  4.        public:  
  5.        void display()  
  6.        {   
  7.              cout<< "Class A ";  
  8.         }  
  9.   };  
  10. class B : public A                       //  derived class declaration.  
  11. {  
  12.     int b;  
  13.     public:  
  14.    void display()  
  15.   {  
  16.         cout<<"Class B";  
  17.   }  
  18. };  

In the above case, the prototype of display() function is the same in both the base and derived class. Therefore, the static binding cannot be applied. It would be great if the appropriate function is selected at the run time. This is known as run time polymorphism.

  • Run time polymorphism: Run time polymorphism is achieved when the object's method is invoked at the run time instead of compile time. It is achieved by method overriding which is also known as dynamic binding or late binding.

Differences b/w compile time and run time polymorphism.

Compile time polymorphismRun time polymorphism
The function to be invoked is known at the compile time.The function to be invoked is known at the run time.
It is also known as overloading, early binding and static binding.It is also known as overriding, Dynamic binding and late binding.
Overloading is a compile time polymorphism where more than one method is having the same name but with the different number of parameters or the type of the parameters.Overriding is a run time polymorphism where more than one method is having the same name, number of parameters and the type of the parameters.
It is achieved by function overloading and operator overloading.It is achieved by virtual functions and pointers.
It provides fast execution as it is known at the compile time.It provides slow execution as it is known at the run time.
It is less flexible as mainly all the things execute at the compile time.It is more flexible as all the things execute at the run time.

C++ Runtime Polymorphism Example

Let's see a simple example of run time polymorphism in C++.

// an example without the virtual keyword.

  1. #include <iostream>    
  2. using namespace std;    
  3. class Animal {    
  4.     public:    
  5. void eat(){      
  6. cout<<"Eating...";      
  7.     }        
  8. };     
  9. class Dog: public Animal      
  10. {      
  11.  public:    
  12.  void eat()      
  13.     {           cout<<"Eating bread...";      
  14.     }      
  15. };    
  16. int main(void) {    
  17.    Dog d = Dog();      
  18.    d.eat();    
  19.    return 0;    
  20. }    

Output:

Eating bread...

C++ Run time Polymorphism Example: By using two derived class

Let's see another example of run time polymorphism in C++ where we are having two derived classes.

// an example with virtual keyword.

  1. #include <iostream>    
  2. using namespace std;    
  3. class Shape {                                        //  base class  
  4.     public:    
  5. virtual void draw(){                             // virtual function  
  6. cout<<"drawing..."<<endl;      
  7.     }        
  8. };     
  9. class Rectangle: public Shape                  //  inheriting Shape class.  
  10. {      
  11.  public:    
  12.  void draw()      
  13.    {      
  14.        cout<<"drawing rectangle..."<<endl;      
  15.     }      
  16. };    
  17. class Circle: public Shape                        //  inheriting Shape class.  
  18.   
  19. {      
  20.  public:    
  21.  void draw()      
  22.    {      
  23.       cout<<"drawing circle..."<<endl;      
  24.    }      
  25. };    
  26. int main(void) {    
  27.     Shape *s;                               //  base class pointer.  
  28.     Shape sh;                               // base class object.  
  29.        Rectangle rec;    
  30.         Circle cir;    
  31.       s=&sh;    
  32.      s->draw();     
  33.         s=&rec;    
  34.      s->draw();      
  35.     s=?    
  36.     s->draw();     
  37. }    

Output:

drawing...
drawing rectangle...
drawing circle...

Runtime Polymorphism with Data Members

Runtime Polymorphism can be achieved by data members in C++. Let's see an example where we are accessing the field by reference variable which refers to the instance of derived class.

  1. #include <iostream>    
  2. using namespace std;    
  3. class Animal {                                          //  base class declaration.  
  4.     public:    
  5.     string color = "Black";      
  6. };     
  7. class Dog: public Animal                       // inheriting Animal class.  
  8. {      
  9.  public:    
  10.     string color = "Grey";      
  11. };    
  12. int main(void) {    
  13.      Animal d= Dog();      
  14.     cout<<d.color;     
  15. }    

Output:

Black



Anurag Rana

Comments

Popular posts from this blog

Standard and Formatted Input / Output in C++

The C++ standard libraries provide an extensive set of input/output capabilities which we will see in subsequent chapters. This chapter will discuss very basic and most common I/O operations required for C++ programming. C++ I/O occurs in streams, which are sequences of bytes. If bytes flow from a device like a keyboard, a disk drive, or a network connection etc. to main memory, this is called   input operation   and if bytes flow from main memory to a device like a display screen, a printer, a disk drive, or a network connection, etc., this is called   output operation . Standard Input and Output in C++ is done through the use of  streams . Streams are generic places to send or receive data. In C++, I/O is done through classes and objects defined in the header file  <iostream> .  iostream  stands for standard input-output stream. This header file contains definitions to objects like  cin ,  cout , etc. /O Library Header Files There are...

Data Warehousing - An Overview

Anurag Information Technology (IT) has historically influenced organizational performance and competitive standing. The increasing processing power and sophistication of analytical tools and techniques have put the strong foundation for the product called data warehouse. There are a number of reasons that any organization should consider a data warehouse, which can be the critical tool for maximizing the organization’s investment in the information it has collected and stored throughout the enterprise. IT managers need to understand the rationale and benefits of data warehouses because they may need to design and implement, or procure this kingpin of business intelligence. The data warehouses are supposed to provide storage, functionality and responsiveness to queries beyond the capabilities of today's transaction-oriented databases. Also data warehouses are set to improve the data access performance of databases. Traditional databases balance the requirement of data access w...

Genotype Representation

Binary Representation This is one of the simplest and most widely used representation in GAs. In this type of representation the genotype consists of bit strings. For some problems when the solution space consists of Boolean decision variables – yes or no, the binary representation is natural. Take for example the 0/1 Knapsack Problem. If there are n items, we can represent a solution by a binary string of n elements, where the x th  element tells whether the item x is picked (1) or not (0). For other problems, specifically those dealing with numbers, we can represent the numbers with their binary representation. The problem with this kind of encoding is that different bits have different significance and therefore mutation and crossover operators can have undesired consequences. This can be resolved to some extent by using  Gray Coding,  as a change in one bit does not have a massive effect on the solution. Real Valued Representation For problems where we want to define ...