polymorphism in c++

Polymorphism in c++-: Polymorphism is one of the crucial features of OOP. It simply means ‘one name, multiple form’. Polymorphism is a Greek word it means ” ability to take more than one ” An operation may exhibit difference behavior in different instance. The behavior depends upon the types of data used in the operation. For example adding two number the operation will generate a sum. if the operands are string then the operation would produce a third string by concatenation. the process making an operator to exhibit difference behaviors in different instance is known as operator overloading.

Types of polymorphism in c++ -: In the c++ programming language the polymorphism has two parts

  1. Compile time polymorphism 
  2. Run time Polymorphism

 

 

Compile time polymorphism -: The overloaded member function are selected for invoking by matching arguments both type and number. this information is known to the compile at the compile time.

compiler is able to select the appropriate compile is able to select the appropriate function for a particular call at the compile time itself. This is called early binding or static binding or static linking. Also known as compile time polymorphism.

For example function overloading

#include <iostream>

#include <stdc++.h> 

using namespace std; 
class netnic 
{ 
	public: 
	

	void func(int x) 
	{ 
		cout << "value of x is " << x << endl; 
	} 
	
	
	{ 
		cout << "value of x is " << x << endl; 
	} 
	
	
	void func(int x, int y) 
	{ 
		cout << "value of x and y is " << x << ", " << y << endl; 
	} 
}; 

int main() { 
	
	netnic vik1; 
	
	
	vik1.func(6); 
	
	
	vik1.func(14.124); 
	
	
	vik1.func(70,45); 
	return 0; 
} 


Output of this program

value of x is 6
value of x is 14.124
value of x and y is 70, 45

 

Run time Polymorphism -: It is known what object are under consideration the appropriate version of the function is invoked since the function is linked with a particular class much later after the compilation, this process is termed as late binding. It is also known as dynamic binding  because this section of the appropriate function is done dynamically at run time

#include <iostream> 

#include <stdc++.h>

using namespace std;

class netnic 
{
public:
virtual void print ()
{ 
    cout<< "print netnic class" <<endl; 
}

void show ()

{
    cout<< "show netnic class" <<endl; }
};

class derived:public netnic
{
public:
void print ()  
{ 
      cout<< "print derived class" <<endl;
 }

void show ()
{ 
     cout<< "show derived class" <<endl; }
};

//main function
int main()
{
   netnic *xptr;
   derived d;
   xptr = &d;
   xptr->print();
   xptr->show();

return 0;
}

Output of this program

Print derived class
Show netnic class

Dynamic binding is a powerful feathers of c++ programming language. This requires to object.

Leave a Reply

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