Explain function overloading in C++ with its return type and signature.

Answer: Function overloading in C++ is the feature of having multiple functions in a class with same name with different return types and signatures. For example in below class we have three functions overloaded.

class A
{
public:	

	//Overloaded function with return type int and void signature
	int func(){
		return 5;
	}

	//Overloaded function with return type int and one "int" parameter
	int func(int a)
	{
		return a;
	}

	//Overloaded function with return type "void" and two "int" parameters
	void func(int a, int b){
	}
};

Function overloading is a compile time polymorphism and function calls are resolved at compile time itself.

It is important to focus that overloaded functions must have different signatures even though the return types are different. For example in below class compiler will throw an error i.e. “overloaded functions differ only by return type”

class A
{
public:	
	int func(int a, int b)
	{
		return a;
	}
	void func(int a, int b){
	}
};

NOTES:

Compiler uses name mangling in C++ to understand different versions of overloaded functions.

Complete example of Function Overloading in C++

Subscribe class has two overloaded functions named “user”. One function will accept only user name and another one will accept user’s name and email address both to subscribe.

class Subscribe
{
public:		
	void user(char* name){
		cout<<"User name:"<<name<<"\n";	
	}	
	void user(char* name, char* email)
	{
		cout<<"User name:"<<name<<"Email:"<<email;		
	}	
};

//-----------TEST : Function Overloading----------
int main()
{
	Subscribe *s = new Subscribe();
	//Subscribe with name only
	s->user("Rakesh");
	//Subscribe with name and email both.
	s->user("Rakesh", "[email protected]");

	return 0;
}

Output:
User name:Rakesh
User name:Rakesh       Email:[email protected]

Related Posts