Friend Functions, Member Pointers & Local Classes in C++
1. What is a Friend Function? (In Simple Words)
In C++, the golden rule of Object-Oriented Programming is Data Hiding: outside functions are strictly forbidden from touching private variables of a class.
Real-Life Analogy: Think of your house. Strangers on the street cannot enter your private bedroom. But if you have a close trusted friend, you invite them inside!
In C++, a Friend Function is an outside non-member function that is given special permission by a class to access its private and protected data members using the friend keyword.
friend keyword in both classes2. Special Rules for Friend Functions (Exam Favorites)
- Not a Member Function: A friend function is NOT a member of the class. It is an outside function.
- No Dot Operator (
.): You cannot call it using an object (writingobj.friendFunc();is an error!). You call it like a regular function:friendFunc(obj);. - Takes Objects as Arguments: Because it is an outside function, it has no
thispointer. You must pass objects into it so it can read their private variables. - Placement Doesn’t Matter: You can write the
frienddeclaration underpublic:orprivate:inside the class; it works exactly the same.
3. Practical Code Example: Comparing Private Data of Two Classes
When two different classes want to compare their private data, a friend function is the easiest solution:
#include <iostream>
using namespace std;
// Forward declaration of ClassB so ClassA knows it exists
class ClassB;
class ClassA {
private:
int valueA;
public:
ClassA(int v) { valueA = v; }
// DECLARING THE FRIEND FUNCTION
friend void findGreatest(ClassA a, ClassB b);
};
class ClassB {
private:
int valueB;
public:
ClassB(int v) { valueB = v; }
// DECLARING THE SAME FRIEND FUNCTION HERE TOO
friend void findGreatest(ClassA a, ClassB b);
};
// DEFINITION: Normal function outside! (Notice: NO 'friend' or '::' here!)
void findGreatest(ClassA a, ClassB b) {
// Can access private 'valueA' and 'valueB' directly!
if (a.valueA > b.valueB) {
cout << "ClassA's value (" << a.valueA << ") is greater!" << endl;
} else {
cout << "ClassB's value (" << b.valueB << ") is greater or equal!" << endl;
}
}
int main() {
ClassA objA(45);
ClassB objB(80);
// Call it like a regular function, NOT with dot operator!
findGreatest(objA, objB); // Prints: ClassB's value (80) is greater or equal!
return 0;
}
4. Friend Classes
Instead of making just one function a friend, you can make an entire class a friend of another class!
class Engine {
private:
int temperature = 95;
public:
// Grants Dashboard full access to all private variables of Engine
friend class DiagnosticDashboard;
};
class DiagnosticDashboard {
public:
void checkEngine(Engine e) {
// Can directly read private variable 'temperature'!
cout << "Engine Temp: " << e.temperature << " deg C" << endl;
}
};
Important Exam Rules About Friendship:
- Friendship is NOT Mutual: If Class B is a friend of Class A, Class A is NOT automatically a friend of Class B.
- Friendship is NOT Transitive: If B is a friend of A, and C is a friend of B, C is NOT automatically a friend of A!
5. Pointer to Class Members (.* and ->*)
C++ allows you to create pointers that point to variables inside a class:
class Sample {
public:
int x;
};
int main() {
// 1. Declare pointer to data member using '::*'
int Sample::*ptr = &Sample::x;
Sample obj;
// 2. Access using an object with '.*'
obj.*ptr = 50;
cout << "Value: " << obj.x << endl; // Prints 50
Sample *pObj = &obj;
// 3. Access using pointer to object with '->*'
cout << "Via object pointer: " << pObj->*ptr << endl; // Prints 50
return 0;
}
6. Local Classes in C++
A class that is defined completely inside a function is called a Local Class.
void calculateSalary() {
// LOCAL CLASS (Lives only inside this function)
class BonusCalculator {
public:
float getBonus(float basic) { return basic * 0.10f; }
};
BonusCalculator bc;
cout << "Bonus: Rs. " << bc.getBonus(50000.0f) << endl;
}
Rules for Local Classes:
- It can only be used inside that specific function.
- It cannot contain static data members.
DAVV Exam Preparation Tips
Frequently Asked 5-Mark Questions:
- What is a friend function in C++? State any four of its characteristics.
Model Answer:- Define: An outside function granted permission to access
privateandprotectedmembers using thefriendkeyword. - 4 characteristics: 1. Not in class scope, 2. Cannot be called with dot operator (
.), 3. Takes objects as parameters, 4. Can be placed underpublic:orprivate:.
- Define: An outside function granted permission to access
- What are the member dereferencing operators in C++?
Model Answer:::*used to declare a pointer to a class member..*used to access a member through an object and a member pointer.->*used to access a member through a pointer to an object and a member pointer.
Frequently Asked 10-Mark Questions:
- Explain the need for friend functions in C++. Does a friend function break data hiding? Write a complete program where a friend function calculates the average marks of two students from two different classes.
Model Answer:- Explain why friend functions are needed: to allow two different classes to share or compare private data, and for operator overloading.
- Explain that it does NOT violate data hiding because the class itself chooses who to grant friendship to.
- Write out complete code with forward declaration of
ClassB, friend function prototype in both classes, and definition calculating(a.marks + b.marks) / 2.0.