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

JAVA Scrollbar, MenuItem and Menu, PopupMenu

ava AWT Scrollbar The  object  of Scrollbar class is used to add horizontal and vertical scrollbar. Scrollbar is a  GUI  component allows us to see invisible number of rows and columns. AWT Scrollbar class declaration public   class  Scrollbar  extends  Component  implements  Adjustable, Accessible   Java AWT Scrollbar Example import  java.awt.*;   class  ScrollbarExample{   ScrollbarExample(){               Frame f=  new  Frame( "Scrollbar Example" );               Scrollbar s= new  Scrollbar();               s.setBounds( 100 , 100 ,  50 , 100 );               f.add(s);   ...

Difference between net platform and dot net framework...

Difference between net platform and dot net framework... .net platform supports programming languages that are .net compatible. It is the platform using which we can build and develop the applications. .net framework is the engine inside the .net platform which actually compiles and produces the executable code. .net framework contains CLR(Common Language Runtime) and FCL(Framework Class Library) using which it produces the platform independent codes. What is the .NET Framework? The Microsoft .NET Framework is a platform for building, deploying, and running Web Services and applications. It provides a highly productive, standards-based, multi-language environment for integrating existing investments with next-generation applications and services as well as the agility to solve the challenges of deployment and operation of Internet-scale applications. The .NET Framework consists of three main parts: the common language runtime, a hierarchical set of unified class librari...

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