C++ Overloading
In C++ language overloading consists of two types.
- Function overloading and
- Operator overloading.
Function Overloading
Two or more functions have the same name but different parameters are called function overloading.
Syntax:
class A { public: void show(int a) { //body of the function. } void show(int a, int b) { //body of the function. } };

Example:
#include <iostream>
using namespace std;
class A
{
public:
void show(int a)
{
cout << "Area of square: "<< a*a << endl;
}
void show(int a, int b)
{
cout << "Area of Rectangle: "<< a*b << endl;
}
};
int main() {
A a;
a.show(5);
a.show(5,7);
return 0;
}
Operator overloading
In C++ Operator Overloading is used to redefine or overload most of the built-in operators. It helps the programmer to use the operators with user-defined data type.
The keyword "operator" followed by the operator of the symbol should be declared.
Syntax:
return_type class_name : : operator op(argument_list) { // body of the function. }
Example:
#include <iostream>
using namespace std;
class Rectangle{
private:
int length, breadth;
public:
Rectangle();
Rectangle(int,int);
Rectangle operator+(Rectangle);
void show_data();
};
Rectangle:: Rectangle(){
length=0;
breadth=0;
}
Rectangle:: Rectangle(int a, int b){
length=a;
breadth=b;
}
Rectangle Rectangle::operator+(Rectangle r1){
Rectangle t;
t.length=length+r1.length;
t.breadth=breadth+r1.breadth;
return t;
}
void Rectangle::show_data(){
cout << "Length: " << length << " Breadth: " << breadth << endl;
cout << "Area of the Rectangle: " << length * breadth << endl;
}
int main(){
Rectangle r1(10,20),r2(20,30),r3;
r3=r1+r2;
r1.show_data();
r2.show_data();
r3.show_data();
return 0;
}
Note:
The operator cannot be used for overloading which are follows:-
Operator | Explanation |
---|---|
. | Direct member or class operator |
.* | Direct pointer to member |
sizeof | Size of operator |
:: | Scope resolution operator |
?: | Ternary or Conditional operator |
# | Preprocessing operator |
Quickly Find What You Are Looking For
OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.