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...

Normalization in DBMS: 1NF, 2NF, 3NF and BCNF in Database

Normalization   is a process of organizing the data in database to avoid data redundancy, insertion anomaly, update anomaly & deletion anomaly.  Anomalies in DBMS There are three types of anomalies that occur when the database is not normalized. These are – Insertion, update and deletion anomaly. Let’s take an example to understand this. Example : Suppose a manufacturing company stores the employee details in a table named employee that has four attributes: emp_id for storing employee’s id, emp_name for storing employee’s name, emp_address for storing employee’s address and emp_dept for storing the department details in which the employee works. At some point of time the table looks like this: emp_id emp_name emp_address emp_dept 101 Nikhil Kangra D001 101 Nikhil Kangra D002 123 Ashish Shimla D890 166 Rahul Pathankot D900 166 Rahul Pathankot D004 The above table is not normalized.  Update anomaly : In the above table we have two rows for employee Nikhil as he belongs ...

Genetic Algorithm: Population, Fitness Function, Parent Selection, Cross over, Mutation

Genetic Algo Population Population is a subset of solutions in the current generation. It can also be defined as a set of chromosomes. There are several things to be kept in mind when dealing with GA population − The diversity of the population should be maintained otherwise it might lead to premature convergence. The population size should not be kept very large as it can cause a GA to slow down, while a smaller population might not be enough for a good mating pool. Therefore, an optimal population size needs to be decided by trial and error. The population is usually defined as a two dimensional array of –  size population, size x, chromosome size . Population Initialization There are two primary methods to initialize a population in a GA. They are − Random Initialization  − Populate the initial population with completely random solutions. Heuristic initialization  − Populate the initial population using a known heuristic for the problem. It has been observed that the e...