Download as PPTX, PDF, TXT or read online from Scribd
Download as pptx, pdf, or txt
You are on page 1of 23
C++ Overloading (Function and Operator)
If we create two or more members having the same
name but different in number or type of parameter, it is known as C++ overloading. In C++, we can overload: • methods, • constructors, and • indexed properties Types of overloading in C++ are: C++ Function Overloading • Function Overloading is defined as the process of having two or more function with the same name, but different in parameters is known as function overloading in C++. • In function overloading, the function is redefined by using either different types of arguments or a different number of arguments. • It is only through these differences compiler can differentiate between the functions. • The advantage of Function overloading is that it increases the readability of the program because you don't need to use different names for the same action Function Overloading Example #include <iostream> using namespace std; class Cal { public: static int add(int a,int b){ return a + b; } static int add(int a, int b, int c) { return a + b + c; } }; int main(void) { Cal C; // class object declaration. cout<<C.add(10, 20)<<endl; cout<<C.add(12, 20, 23); return 0; } When the type of the arguments vary #include<iostream> using namespace std; int mul(int,int); float mul(float,int); int mul(int a,int b) { return a*b; } float mul(double x, int y) { return x*y; } int main() { int r1 = mul(6,7); float r2 = mul(0.2,3); std::cout << "r1 is : " <<r1<< std::endl; std::cout <<"r2 is : " <<r2<< std::endl; return 0; } Function Overloading and Ambiguity When the compiler is unable to decide which function is to be invoked among the overloaded function, this situation is known as function overloading. When the compiler shows the ambiguity error, the compiler does not run the program. Causes of Function Overloading: • Type Conversion. • Function with default arguments. • Function with pass by reference. #include<iostream> using namespace std; void fun(int); void fun(float); void fun(int i) { std::cout << "Value of i is : " <<i<< std::endl; } void fun(float j) { std::cout << "Value of j is : " <<j<< std::endl; } int main() { fun(12); fun(1.2); return 0; } Explanation • example shows an error "call of overloaded 'fun(double)' is ambiguous". • The fun(10) will call the first function. • The fun(1.2) calls the second function according to our prediction. But, this does not refer to any function as in C++, all the floating point constants are treated as double not as a float. • If we replace float to double, the program works. • Therefore, this is a type conversion from float to double.