What is function overloading Polymorphism type in C++?

Answer: In C++ function overloading is a compile time polymorphism as it get resolved on compile time itself. There are two types of polymorphism available in c++ object oriented programming i.e. compile time and run time polymorphism. The run time polymorphism code example in cpp can be read here.

Function get resolved at compile time means, during compilation of the code itself when compiler see a function call, it will decide which version of function to call, out of multiple overloaded functions, depending upon signature of the function i.e. type and arguments.

For example, in below class A, we have two overloaded functions named func(). During compilation of the code, when compiler will see a call in main program e.g. obj.func(5); it will choose one argument overloaded function i.e. void func(int a).

class A{
public:
	//two overloaded functions
	void func(int a){cout<<"func(int a)"<<"\n";}
	void func(int a,int b){cout<<"func(int a)"<<"\n";}
	
};
int main(){
	
	A obj;
	
	//At compile time itself compiler will decide which overloaded func to call
	//by function signature.
	obj.func(5);

	return 0;
}

NOTES:

1)Class constructor overloading in C++ is also a compile time polymorphism. For example,

class A{	
public:

	//constructor overloading
	A(){cout<<"Constructor: A()"<<"\n";}
	A(int a){cout<<"Constructor: A(int a)"<<"\n";}
	A(int a,int b){cout<<"Constructor: A(int a,int b)"<<"\n";}

};

2)Operator overloading is also know as compile time polymorphism.

3)Compile time polymorphis is also known as “Static binding” in C++.

Read: Advantage of constructor overloading in C++.

Related Posts