Concept of Friend in C++

Mannan Ul Haq
0

Friend Functions and Friend Classes:

In object-oriented programming, a friend function or a friend class is a concept that allows a function or a class to access private and protected members of another class. This feature breaks the encapsulation principle to some extent, but it can be useful in certain scenarios where tight coupling between classes is required or when specific functionalities need privileged access to private members.


1. Friend Function:

A friend function is a non-member function that has access to the private and protected members of a class. It is declared within the class that wants to provide access, using the `friend` keyword. The friend function is then defined outside the class scope. Here's an example to illustrate the concept:


class MyClass
{
private:
	int privateData;

public:
	MyClass(int data)
	{
		privateData = data;
	}

	friend void friendFunction(MyClass& obj);
};

void friendFunction(MyClass& obj)
{
	obj.privateData = 42;  // Accessing private member of MyClass
}

int main()
{
	MyClass myObj(10);

	friendFunction(myObj);
	// privateData in myObj is now 42

	return 0;
}


In the example above, the `friendFunction` is declared as a friend function within the `MyClass` definition. It can access the private member `privateData` of any `MyClass` object. Inside the friend function, we can manipulate the private member directly.


2. Friend Class:

A friend class is a class that is granted access to the private and protected members of another class. To declare a friend class, the `friend` keyword is used within the class definition. Here's an example to illustrate the concept:


class MyClass
{
private:
	int privateData;

public:
	MyClass(int data)
	{
		privateData = data;
	}

	friend class FriendClass;
};

class FriendClass
{
public:
	void modifyData(MyClass& obj, int newData)
	{
		obj.privateData = newData;  // Accessing private member of MyClass
	}
};

int main()
{
	MyClass myObj(10);

	FriendClass friendObj;

	friendObj.modifyData(myObj, 42);
	// privateData in myObj is now 42

	return 0;
}


In the example above, the `FriendClass` is declared as a friend class within the `MyClass` definition. The `FriendClass` can access the private member `privateData` of any `MyClass` object. In the `modifyData` function of `FriendClass`, we can manipulate the private member directly.


Tags

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !