Need a project done?

C++ Programming Developer

Search This Blog

Showing posts with label friend class. Show all posts
Showing posts with label friend class. Show all posts

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;
}

Friend Class C++


#include <iostream>
using namespace std;

class a{
friend class b;//a has granted friendship to b.
public:
//public members...
private:
int a_mem;
};

class b{
public:
int get_member_of_class_a(a &instance_of_a){
return instance_of_a.a_mem; //Since b is a friend of a so b should have access
//to all members of class a's objects.
//Without using friend statement in class a, we cannot access private member of class 'a' in class 'b' using object.private_member.
}
void set_member_of_class_a(a& instance_of_a,int value){
instance_of_a.a_mem = value;
}
private:
//private members...
};

int main(){
b obj_b;
a obj_a;
cout << "We access class a's private member through class b << endl:
obj_b.set_member_of_class_a(obj_a,5);
cout << obj_b.get_member_of_class_a(obj_a) << endl;
return 0;
}
"Don't let anyone ever make you feel like you don't deserve what you want."