≡ Menu

How to Use Friend Modifier in C++ with Example Code

You would consider someone as your friend, if you trust him/her and thereafter you would grant your friend some higher level of privilege.

Some might say a friend of your friend is also your friend. But, as we will see that is not that case in C++.

In C++, you should exactly state who you trust. This way, you would have more control on your friends, as well as they could have more restrictions on you as a friend.

How to Define Friend Modifier

The following are few situations where you could use friend modifier:

  • It could be used in a stand alone functions, methods of different class, complete class, template function or even template class.
  • You could also have non-member function with friend modifier. In that case, that function will not have “this” as a pointer, and that function would have access to all the data from your class.
  • If you only like to restrict one method (or few selective methods) to use data from other class, you would not need to call that class a friend class, which is left for more extreme situations when you could call whole class a friend.
  • Also, template functions and classes are similar to usual functions and classes, but they don’t care about the type of data they are handling, and they could have friends too.

In a way, you could say that friend overpowers modifiers like private, or public, or protected. In another words friend modifier nullifies restrictions gained from already mentioned access restrictions.

So, how do we implement a friend modifier?

class CSomeClass
{
...
friend someType FriendFunction( SomeArguments);
...
};

In the above code snippet, you use “friend” modifier to inform your compiler that you will trust FriendFunction. In this case, you should inform your compiler about the function name, return data type, and arguments you are using.

After that, you implement your stand alone function as a side of class implementation, but you don’t use friend modifier:

someType FriendFunction( SomeArguments);

If you would like to have just one method as a friend to your class, you would call it as mentioned below.

class CSomeClass {
...
friend Return_Type CSomeOtherClass::SomeMethod(Different_Data_Types as arguments);
...
};

For extreme situations, you could call whole class a friend class, that way friend class will have access to data that is usually not visible by other entities, and thereupon hidden data might be unobtainable.

To implement this, you could use the following code snippet:

class CSomeClass;
...
class CFriendClass
{
...
void SomeMethod( CSomeClass object);
...
};

Next, you create a class that will have CFriendClass as a friend.

class CSomeClass
{
...
friend class CFriendCalss;
...
};

Finally, you would go into implementation of your method:

void CFriendClass::SomeMethod( CSomeClass object) {...}

It might be a good idea to create few simple examples that will clear up some syntax issues you might have.

If you decide to practice, I would recommend that you to create class CDot with two values: x and y, and after you create a non-member function double distance( CDot a, CDot b);. This would calculate distance from first to second dot.

For a friend class, I would recommend you to use same class CDot and its friend class CLineSegment to create one line segment from two CDot objects.

Now, we will consider few properties that friend classes have.

First one is very easy to understand. If class A is friend of class B, it does not mean that class B will be friend of class A, without some extra coding. If you really need A to be friend of B as well, you would need to state that also.

Next interesting property is sometimes called transitivity. For example, let’s take a situation where you are facing three classes: Class A, B and C.

If you have B as a friend of A, and you have C as the friend of B, it might be reasonable to expect from C to be friend of A. This time, friend of your friend is not your friend. As you might conclude, you would need to state that C is a friend of A as well.

Friend Modifier Example Code – Problem Definition

In order to explain friend modifier we will create an example. This will illustrate how you could overload operators, and we will also explain how to use ostream and istream as objects that will present and import data from user to our class.

For our exercise, our task is to create class CComplexNumber.

  • Just to refresh your math memory, the following are some properties of complex number:
  • This problem will help you solve something like this: ax*x + b*x + c =0.
  • Complex number has two parts: real and imaginary. That imaginary part is multiple of square root of -1.
  • For this, it is usually denoted like this: z = x + i*y.
  • Apart from this, you also have polar form of complex number and exponential form as well.

Friend Modifier Example Code – Solution

The following is the example C++ code that uses friend modifier to solve our problem.

#include <iostream>

using namespace std;

class CKomplexNumber
{
private:
double dX,dY;

public:
CKomplexNumber(const double x, const double y)
{dX=x;dY=y;}
CKomplexNumber(){;//This is not a smiley}
CKomplexNumber
operator+(const CKomplexNumber& z)
{
CKomplexNumber temp=*this;
temp.dX += z.dX; temp.dY += z.dY;
return temp;
}
friend ostream&
operator<<(ostream& out, const CKomplexNumber z);
friend istream&
operator>>(istream& in, CKomplexNumber& z);
};
ostream&
operator<<(ostream& out, const CKomplexNumber z)
{
cout<<"Complex number is"<<endl;
out<<z.dX<<" + "<<z.dY<<" i"<<endl;
return out;
}
istream&
operator>>(istream& in, CKomplexNumber& z)
{
cout<<"Imput real and imaginary part"<<endl;
in>>z.dX>>z.dY;
return in;
}

int
main(void)
{
CKomplexNumber Z1;
cout<<"First complex number is="<<endl;
cin>>Z1;
cout<<Z1;

CKomplexNumber Z2;
cout<<"Second complex number is="<<endl;
cin>>Z2;
cout<<Z2;
CKomplexNumber Z3;
cout<<"Third complex number is="<<endl;
cin>>Z3;
cout<<Z3;
CKomplexNumber Zr(0,0);
Zr = Z1 + Z2 + Z3;
cout<<Zr;

return EXIT_SUCCESS;
}

Friend Modifier Example Code – Explanation

In the above sample code:

  • In CComplexNumber class we have data that is used to describe values of complex number. This is dX and dY and they are of double data type.
  • We have constructors as well, you might even add few additional constructor and destructor of your own.
  • In order to enable most logical syntax you would use operator +. Just to be clear, you don’t need to type something like this: Zr.AddComplexNumbers(Z1,Z2);
  • Instead, it will be better if you do something simple like this: Zr = Z1 + Z2;
  • We have two overloaded operators: “>>” and “<<". You could say that we will not need our set and get methods, but they have their place as well. Or, you could say that you use methods get and set very seldom.
  • Now we will analyse code in the main function. First, we instantiate one object called Z1 then we input its values, that are real and imaginary part.
  • After that Z1 is presented to user. Next few steps are pretty similar therefore we would not need to go into the details all over again.
    Finally, we add those three complex number and store result into Zr, and we present our results to user.

Suggested Improvements to the Code

The following are few things you can do to improve the above code to learn more about how to use friend modifier:

  • Broaden the solution with support to polar and exponential form of complex numbers.
  • Next thing you could do is to have inherited classes, and also you could have three types of complex numbers and then you try to have three classes as parents. You could put your friend functions to transform those complex numbers from one form to another. If you are new to inheritance, this might help: How to Use C++ Inheritance and Abstract Class with Code Examples
  • We have overloaded only three operators: operator+, operator>> and operator<<. You could add few more overloaded operators too.
  • Now, you might start to think about: overflow, underflow and bad inputs, as some bad things that could happen with your code, and if you wish to use your class in real life situations, that would probably be ultimate goal for most of us, you should find ways to make your code more robust.
  • On a related note, you might find this helpful to make your code robust: 10 Tips for C and C++ Performance Improvement Code Optimization
  • Create an user-friendly complex number calculator by using the above code snippet as a base.

Relationship to Encapsulation and Inheritance

After you have understood how friend modifier works and you start to create practical rules, you might ask you self how is it related to encapsulation?

Encapsulation is one of the major principles of OOP. Some might think that friend modifier is ruining concept of OOP. But it does not, it will allow exception that is needed and that way it would preserve encapsulation, with minimum divergence, due to technical issues.

Sometimes it is good to think of it, as interface to a class. That is reason why you could say that classes have some relationship in that case.
Placing your data under public modifier would be example that works against encapsulation.

Another question you might ask is: Do I inherit friends from parent class?

We have explained inheritance. In most situations, you have need for public inheritance, which means that you are broadening base class with new features and this excludes the private members.
The answer to this question is no. We do not inherit friends from our parent class.

Final Thoughts on Friend Method, Operator, Class

  • Friend modifier is useful, and it has a place in Object Oriented Programming. We would also need to say that friend functions would be very useful in situations when you are trying to avoid placing your data to public.
  • One example is application of operators: “>>” and “<<“. It could be applied with some other operators, but you should avoid it if possible.
    Sometimes this will reduce the complexity in the amount of code you have to write to solve certain problems.
  • It could be used when you have some relationships between two objects of same kind, or even two or more objects of different type. For example, you would need to compare them, or create new object from those few objects you have.
  • One of situations when you could deploy this is when you need to transform object of one type to another type.
  • In my opinion, it might be a good idea to create friend part of class where you would state friends of a class, that way code would be more organized and systematic. It might be a good idea to have same thing like that with virtual methods as well.

Additional Exercise to Practice Friend Modifier

The following are few additional exercise for you to use Friend modifier and solve these specific problems.

  • Create solution for 2 dimensional vector, 3 dimensional vector, n dimensional vector using friend modifier. If you are new to vector, this might help: STL Tutorial: How to use C++ Vector
  • Create class CDot, with int coordinates and two data, one for each of the projections. Don’t forget to use friend functions. Create non member function, which will calculate distance among two dots.
  • To measure temperature you have: Kelvin, Celsius, Fahrenheit. Convert the temperature between these three types. This means that you could create abstract class CTemprerature, and use it as a base class for: CKelvin, CCelsius and CFarenhite. In order to convert those objects, you could use stand alone functions as friends.
  • Create class CCalendarDate. That could be done if you have three classes: CDay, CMonth, CYear. After, you have created class CCalendarDate, you could create non member function that will calculate how many days is difference among two calendar dates.
  • For time measurement, your task is to create class CTime. You need to consider both 12 and 24 hour format.
    Create template class CMatrix with adequate friends.
  • If you like math and studied it, or if you just like games of luck, this might be your favorite. You are required to model two classes: CCup and CBall. In one cup you would place small balls that are colored. Colors could be different. You could have more cups with small balls and you should calculate the probability to pick one of the small balls from each of the cups you have. You should have ability to create solution that will allow you to pick small ball from one cup and place it into other cups.
Add your comment

If you enjoyed this article, you might also like..

  1. 50 Linux Sysadmin Tutorials
  2. 50 Most Frequently Used Linux Commands (With Examples)
  3. Top 25 Best Linux Performance Monitoring and Debugging Tools
  4. Mommy, I found it! – 15 Practical Linux Find Command Examples
  5. Linux 101 Hacks 2nd Edition eBook Linux 101 Hacks Book

Bash 101 Hacks Book Sed and Awk 101 Hacks Book Nagios Core 3 Book Vim 101 Hacks Book

Comments on this entry are closed.