Concept of Friendship in C++

Written by Hamza on. Posted in C++

Our progress in this series of articles on object oriented programming in C++ has been deliberately slow so that readers would have time to grasp the basics of classes and their objects before moving on to their practical usage. Let us pick up the pace a little bit. We will now move to the concept of friendship in c++. From here we can go on to more advanced concepts like inheritance and polymorphism.

So far, we have dealt with two types of data members within classes, i.e, private and public data members. As I have explained, public data members are accessible to the world outside the class (through an object of course). On the other hand, private data members are only accessible within the class, and could not, so far as we knew, be accessed without using public member functions. However, there IS another way to access  private data members in a class without having to deal with the public function interface. Private data members are accessible from friend functions or classes.

A class or a function can be made a friend by using the ‘friend’ keyword. The basic syntax is as follows:

class someclass


//private and public interface

friend <prototype_of_function>



The following example would make this even clearer. We will use our favourite fraction class. Here we want a function that will take a fraction and multiple the numerator and denominator data members by 2. But we want to implement this without using any getters or setters. Here is how we will achieve this:


class fraction


. private:

. int numerator;

. int denominator;

. public:

//assume overloaded constructor declared

. friend void double_fields(fraction obj);


.  void double_fields(fraction obj)

. {

.  obj.numerator = obj.numerator * 2;

.  obj.denominator = obj.denominator * 2;

.  //directly accessing private data members!

. }

void main()


.  fraction obj(2,3); //overloaded constructor that sets values of numerator = 2 and denominator = 3

.  double_fields(obj);


Here we can see that the obj fraction will now contain: numerator = 4 and denominator = 6. Thus, we have successfully accessed the private data members outside the class without using any public functions whatsoever. This is how friendship in C++ works. A class or a function should only be made a friend when we want to give it the exclusive rights to its private (and protected, more on that later) data members.

Friendship only touches on a very important concept in object oriented programming in C++: how to link more than one class or function in a program. The bond of friendship between class and function may be strong, but as we will see in the next article, the bond of inheritance is even stronger. See you soon guys!

Tags: , , ,

Trackback from your site.

Leave a comment