Operator Overloading in C++
Master C++ with Real-time Projects and Kickstart Your Career Start Now!!
Program 1
// Operator overloading
#include<iostream>
using namespace std;
class Test
{
private:
int a,b,c;
public:
Test(int a,int b,int c)
{
// cout<<"I am constructor";
this->a=a;
this->b=b;
this->c=c;
}
void display()
{
cout<<a<<" "<<b <<" "<<c<<endl;
}
void operator-();
};
void Test::operator-()
{
//cout<<"This is operator - method";
a=-a;
b=-b;
c=-c;
}
int main()
{
system("cls");
Test T1(10,20,30);
T1.display(); // 10 20 30
-T1; // T1.operator-()
T1.display(); // -10 -20 -30
return 0;
}
// int a=700; // global
// class Test
// {
// public:
// void abc();
// };
// void Test::abc()
// {
// cout<<"abc method";
// }
// int main()
// {
// system("cls");
// int a=60; //local
// cout<<a<<endl << ::a;
// return 0;
// }
// system("cls");
// cout<<"Hello"; //extertion
// int a;
// a=5<<3; // left shift
// cout<<a;
// int n;
// cout<<"Enter a number";
// cin>>n; // insertion
// n=20>>2; // right shift
// cout<<n;Program 2
#include<iostream>
using namespace std;
class Test
{
private:
int a,b,c;
public:
Test(int a,int b,int c)
{
// cout<<"I am constructor";
this->a=a;
this->b=b;
this->c=c;
}
void display()
{
cout<<a<<" "<<b <<" "<<c<<endl;
}
void operator++();
void operator++(int);
};
void Test::operator++()
{
cout<<"\n Pre increment\n";
++a;
++b;
++c;
}
void Test::operator++(int)
{
cout<<"\n Post increment\n";
++a;
++b;
++c;
}
int main()
{
system("cls");
Test T(10,20,30);
T.display();
// ++T; //// T.operator++() pre increment
T++; //post increment T.operator++(int)
T.display();
return 0;
} Did we exceed your expectations?
If Yes, share your valuable feedback on Google

