Need a project done?

C++ Programming Developer

Search This Blog

Operator Overloading C++

//Adding two objects of different classes.

//This example of operator overloading uses friend functions and friend class to set and get the value of 'x', a private member.
//Before this example, see an easier example.

#include <iostream>
using namespace std;

class b{
int x;
public:
friend void setX(b& obj_b, int value);
friend int getX(b& obj_b);
friend class a;
};
class a{
int x;
public:
friend void setX(a& obj_a, int value);
friend int getX(a& obj_a);
int operator+(b &obj);
};

int main(){
a obj_a;
b obj_b;
setX(obj_a,5);
setX(obj_b,10);
cout << "obj_a = " << getX(obj_a) << endl;
cout << "obj_b = " << getX(obj_b) << endl;
cout << "\nSUM of objects of different classes: " << obj_a + obj_b << endl;
return 0;
}

int a::operator+(b &obj){
return x + obj.x;
}

void setX(a& obj_a, int value){
obj_a.x = value;
}
void setX(b& obj_b, int value){
obj_b.x = value;
}
int getX(a& obj_a){
return obj_a.x;
}
int getX(b& obj_b){
return obj_b.x;
}

No comments:

Post a Comment

"Don't let anyone ever make you feel like you don't deserve what you want."