0% found this document useful (0 votes)
43 views

Function Overloading

C++ allows function overloading by defining multiple functions with the same name but different parameters. The compiler determines which function to call based on the types of arguments passed. Functions can be overloaded based on the number and types of arguments but not the return type. An example demonstrates overloading the print function to handle int, float, and char* types.

Uploaded by

Rooshan Javed
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views

Function Overloading

C++ allows function overloading by defining multiple functions with the same name but different parameters. The compiler determines which function to call based on the types of arguments passed. Functions can be overloaded based on the number and types of arguments but not the return type. An example demonstrates overloading the print function to handle int, float, and char* types.

Uploaded by

Rooshan Javed
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 2

Function overloading in C++:

C++ allows you to specify more than one definition for a function name in the same
scope, which is called function overloading.

An overloaded declaration is a declaration that had been declared with the same name as
a previously declared declaration in the same scope, except that both declarations have
different arguments and obviously different definition (implementation).

When you call an overloaded function, the compiler determines the most appropriate
definition to use by comparing the argument types you used to call the function with the
parameter types specified in the definitions.

Function overloading in C++:

You can have multiple definitions for the same function name in the same scope. The
definition of the function must differ from each other by the types and/or the number of
arguments in the argument list. You can not overload function declarations that differ
only by return type.

Following is the example where same function print() is being used to print different
data types:

#include <iostream>
using namespace std;

class printData
{
public:
void print(int i) {
cout << "Printing int: " << i << endl;
}

void print(double f) {
cout << "Printing float: " << f << endl;
}

void print(char* c) {
cout << "Printing character: " << c << endl;
}
};

int main(void)
{
printData pd;

// Call print to print integer


pd.print(5);
// Call print to print float
pd.print(500.263);
// Call print to print character
pd.print("Hello C++");

return 0;
}

When the above code is compiled and executed, it produces following result:

Printing int: 5
Printing float: 500.263
Printing character: Hello C++

You might also like