OOP-Weekend Lecture 05
OOP-Weekend Lecture 05
Normally, only members of a class can access its private/protected data. But sometimes, you want a non-
member function or another class to access this data. That's where friend comes in.
Task 1
Write a class `Number` with a private integer. Use a friend function to add two `Number` objects and
#include <iostream>
class Number
private:
int value;
public:
Number(int v)
value=v;
};
int main() {
Number a(5);
Number b(10);
}
Task 2
Create a class `Counter` with a private member `count`. Write a friend function `increment()` that
#include <iostream>
using namespace std;
class Counter {
private:
int count;
public:
Counter()
{
count =0;
}
int main() {
Counter c; increment(c); return 0;
}
Task 3
Create two classes `A` and `B`, each with a private integer. Write a friend function `showSum()` that can
class A;
class B;
class A { private:
int x;
public:
A(int val) : x(val) {} friend void
showSum(A, B);
};
class B { private:
int y;
public:
B(int val) : y(val) {} friend void
showSum(A, B);
};
void showSum(A a, B b) {
cout << "Sum: " << a.x + b.y << endl;
}
int main() {
A a(3);
B b(7);
showSum(a, b);
return 0;
}
Task 4
Create a class `Person` with a private member `age`. Write a friend function `compareAges()` that compares
public:
Person(int a) : age(a) {}
int main() {
Person p1(25), p2(30);
compareAges(p1, p2); return 0;
}