3.5 Function Overloading
3.5 Function Overloading
--Prof. S.N.Shelke
C++ Overloading
If we create two or more members having the same name but different
1. methods,
2. constructors, and
return a + b + c;
}
};
int main() {
Cal C; // class object declaration.
cout<<C.add(10, 20)<<endl;
cout<<C.add(12, 20, 23);
return 0;
}
Function Overloading and Ambiguity
When the compiler shows the ambiguity error, the compiler does not run
the program.
#include <iostream>
using namespace std;
class Cal
{
public:
void add(int a,int b)
{
int ans=a+b+100;
cout<<a+b<<endl;
}
void add(float x, float y)
{
float ans=x+y+200;
cout<<ans<<endl;
}
};
int main()
{
Cal C; Output:
int y=10;
C.add(10,20); 130
return 0;
}
#include <iostream>
using namespace std;
class Cal
{
public:
void add(int a,int b)
{
int ans=a+b;
cout<<a+b<<endl;
}
void add(int x, int y, int z=5)
{
float ans=x+y+z;
cout<<ans<<endl;
}
};
int main()
{
Cal C;
int y=10;
C.add(10,20,30);
C.add(10,20);
return 0;
}
#include <iostream>
using namespace std;
class Cal
{
public:
void add(int x)
{
x=x+100;
cout<<x<<endl;
}
void add(int &p)
{
p=p+200
cout<<p<<endl;
}
};
int main()
{
Cal C;
int y=10;
C.add(y);
return 0;
}
Prof. S. N. Shelke
(Assistant Professor)
Department of Computer
Engineering
Sinhgad Academy of Engineering,
Kondhwa, Pune