C++ Overloading
C++ Overloading is a condition when two or more members have the same name with different parameter type or a different number of parameter. C++ overloading is two types:
- Function overloading
- Operator overloading
C++ Function Overloading
When two or more function having the same name are different in their parameter is called function overloading.C++ Function Overloading Example
This example calculates the area of two different polygons.#include<iostream>
using namespace std;
class Polygon
{
public:
void area(int x)
{
cout << "area of cube " << x*x << endl;
}
void area(int x, int y)
{
cout << "area of ractangle " << x*y<< endl;
}
};
int main() {
Polygon obj;
obj.area(4);
obj.area(3,4);
return 0;
}
area of cube 16 area of rectangle 12
C++ Operator Overloading
C++ provides the functionality to redefine or overload the existing operators in C++. Operator overloading is used to perform an operation on user define the data type.C++ Operator Overloading Example
#include <iostream>
using namespace std;
class operatorEx
{
private:
int num;
public:
operatorEx(): num(10){
}
void operator --()
{
num = num-1;
}
void print() {
cout<<"num is: "<<num;
}
};
int main()
{
operatorEx obj;
--obj; // calling of a function "void operator --()"
obj.print();
return 0;
}
num is: 9