What is the friend keyword in C++?

Written by

Garvit Gulati

The friend keyword in C++ allows the programmer to declare friend functions and classes. Let us understand further what are friend functions and classes.

Data hiding is an important concept of Object-Oriented Programming (OOP). It as achieved with the help of classes and access specifiers. They restrict non-member functions from accessing private and protected data members, therefore, hiding data.

Sometimes, due to this restriction, programmers end up writing long codes which can be otherwise done with a shorter method but compromising data hiding.

To solve this, a friend keyword is used. By declaring a friend function, we allow the function to access public and private variables of the class without being a member of the function. Similarly, we can declare a friend class in which all the member functions of the friend class becomes friend functions.

For example,

class frnd{
	private:
		void somefunc();
};

int frndFUNC(int a) {}

class A{
	friend class frnd;
	friend int frndFUNC(int a);
};

Here, both somefunc() and frndFUNC() can access the private and protected members of class A without being the members of class A.

Some important points about friend functions and classes:

  1. Declarations of friend functions and classes are always made inside the class definition(can be anywhere either in public and private)
  2. Friend functions and classes are declared by the implementor i.e. only the class can define its friend functions and classes, a function or class cannot declare itself a friend of a class
  3. Friend classes can access the data members of the class but not vice versa i.e. Class frnd can access the data members of class A but class A cannot access members of class frnd.
  4. Friend functions are not inherited.
What is the friend keyword in C++?