Search

8.13 — Friend functions and classes

For much of this chapter, we’ve been preaching the virtues of keeping your data private. However, you may occasionally find situations where you will find you have classes and functions outside of those classes that need to work very closely together. For example, you might have a class that stores data, and a function (or another class) that displays the data on the screen. Although the storage class and display code have been separated for easier maintenance, the display code is really intimately tied to the details of the storage class. Consequently, there isn’t much to gain by hiding the storage classes details from the display code.

In situations like this, there are two options:
1) Have the display code use the publicly exposed functions of the storage class. However, this has several potential downsides. First, these public member functions have to be defined, which takes time, and can clutter up the interface of the storage class. Second, the storage class may have to expose functions for the display code that it doesn’t really want accessible to anybody else. There is no way to say “this function is meant to be used by the display class only”.

2) Alternatively, using friend classes and friend functions, you can give your display code access to the private details of the storage class. This lets the display code directly access all the private members and functions of the storage class, while keeping everyone else out! In this lesson, we’ll take a closer look at how this is done.

Friend functions

A friend function is a function that can access the private members of a class as though it were a member of that class. In all other regards, the friend function is just like a normal function. A friend function may be either a normal function, or a member function of another class. To declare a friend function, simply use the friend keyword in front of the prototype of the function you wish to be a friend of the class. It does not matter whether you declare the friend function in the private or public section of the class.

Here’s an example of using a friend function:

In this example, we’ve declared a function named reset() that takes an object of class Accumulator, and sets the value of m_value to 0. Because reset() is not a member of the Accumulator class, normally reset() would not be able to access the private members of Accumulator. However, because Accumulator has specifically declared this reset() function to be a friend of the class, the reset() function is given access to the private members of Accumulator.

Note that we have to pass an Accumulator object to reset(). This is because reset() is not a member function. It does not have a *this pointer, nor does it have an Accumulator object to work with, unless given one.

Here’s another example:

In this example, we declare the isEqual() function to be a friend of the Value class. isEqual() takes two Value objects as parameters. Because isEqual() is a friend of the Value class, it can access the private members of all Value objects. In this case, it uses that access to do a comparison on the two objects, and returns true if they are equal.

While both of the above examples are fairly contrived, the latter example is very similar to cases we’ll encounter in chapter 9 when we discuss operator overloading!

Multiple friends

A function can be a friend of more than one class at the same time. For example, consider the following example:

There are two things worth noting about this example. First, because PrintWeather is a friend of both classes, it can access the private data from objects of both classes. Second, note the following line at the top of the example:

This is a class prototype that tells the compiler that we are going to define a class called Humidity in the future. Without this line, the compiler would tell us it doesn’t know what a Humidity is when parsing the prototype for PrintWeather() inside the Temperature class. Class prototypes serve the same role as function prototypes -- they tell the compiler what something looks like so it can be used now and defined later. However, unlike functions, classes have no return types or parameters, so class prototypes are always simply class ClassName, where ClassName is the name of the class.

Friend classes

It is also possible to make an entire class a friend of another class. This gives all of the members of the friend class access to the private members of the other class. Here is an example:

Because the Display class is a friend of Storage, any of Display’s members that use a Storage class object can access the private members of Storage directly. This program produces the following result:

6.7 5

A few additional notes on friend classes. First, even though Display is a friend of Storage, Display has no direct access to the *this pointer of Storage objects. Second, just because Display is a friend of Storage, that does not mean Storage is also a friend of Display. If you want two classes to be friends of each other, both must declare the other as a friend. Finally, if class A is a friend of B, and B is a friend of C, that does not mean A is a friend of C.

Be careful when using friend functions and classes, because it allows the friend function or class to violate encapsulation. If the details of the class change, the details of the friend will also be forced to change. Consequently, limit your use of friend functions and classes to a minimum.

Friend member functions

Instead of making an entire class a friend, you can make a single member function a friend. This is done similarly to making a normal function a friend, except using the name of the member function with the className:: prefix included (e.g. Display::displayItem).

However, in actuality, this can be a little trickier than expected. Let’s convert the previous example to make Display::displayItem a friend member function. You might try something like this:

However, it turns out this won’t work. In order to make a member function a friend, the compiler has to have seen the full declaration for the class of the friend member function (not just a forward declaration). Since class Storage hasn’t seen the full declaration for class Display yet, the compiler will error at the point where we try to make the member function a friend.

To resolve this, we can switch the order of class Display and class Storage. We will also need to move the definition of Display::displayItem() out of the Display class declaration, because it needs to have seen the definition of class Storage first.

Now, this will compile, and Display::displayItem is a friend of class Storage.

However, a better solution would have been to put each class declaration in a separate header file, with the function bodies in corresponding .cpp files. That way, all of the class declarations would have been visible immediately, and no rearranging of classes or functions would have been necessary.

Summary

A friend function or class is a function or class that can access the private members of another class as though it were a member of that class. This allows the friend or class to work intimately with the other class, without making the other class expose its private members (e.g. via access functions).

Friending is uncommonly used when two or more classes need to work together in an intimate way, or much more commonly, when defining overloading operators (which we’ll cover in chapter 9).

Note that making a class a friend only requires as forward declaration that the class exists. However, making a specific member function a friend requires the full declaration for the class of the member function to have been seen first.

Quiz time

1) In geometry, a point is a position in space. We can define a point in 3d-space as the set of coordinates x, y, and z. For example, the Point(2.0, 1.0, 0.0) would be the point at coordinate space x=2.0, y=1.0, and z=0.0.

In physics, a vector is a quantity that has a magnitude (length) and a direction (but no position). We can define a vector in 3d-space as an x, y, and z value representing the direction of the vector along the x, y, and z axis (the length can be derived from these). For example, the Vector(2.0, 0.0, 0.0) would be a vector representing a direction along the positive x-axis (only), with length 2.0.

A Vector can be applied to a Point to move the Point to a new position. This is done by adding the vector’s direction to the point’s position to yield a new position. For example, Point(2.0, 1.0, 0.0) + Vector(2.0, 0.0, 0.0) would yield the point (4.0, 1.0, 0.0).

Points and Vectors are often used in computer graphics (the point to represent vertices of shape, and vectors represent movement of the shape).

Given the following program:

1a) Make Point3d a friend class of Vector3d, and implement function Point3d::moveByVector()

Show Solution

1b) Instead of making class Point3d a friend of class Vector3d, make member function Point3d::moveByVector a friend of class Vector3d.

Show Solution

1c) Reimplement the solution to quiz question 1b using 5 separate files: Point3d.h, Point3d.cpp, Vector3d.h, Vector3d.cpp, and main.cpp.

Thanks to reader Shiva for the suggestion and solution.

Show Solution

8.14 -- Anonymous variables and objects
Index
8.12 -- Static member functions

98 comments to 8.13 — Friend functions and classes

  • sanjay

    hey its great to have a website like this
    i didn’t buy my cp book till my exams even then i stood 3rd in my class…


    sanjay

  • jagadeesh

    c++ programm.
    member function of class can access private members,than we we need friend function,what is the use of this please iam in confusion

    • Making a function a friend of some class means that function has access to the classes private member variables (even though that function is not a member of the class). The Humidity/Weather example above shows an example of this: PrintWeather() is using the private members of Humidity and Weather (which it would normally not have access to, because they are private). However, it is allowed to do this because it has been made a friend.

  • K D Joshi

    Is it compulsory to declare a function(which is required to be a friend function) in that class itself?
    Suppose there is a class named FUN. It has some private and some public elements. Now I want a function called SOME to be a friend of FUN. So, is it MUST to declare SOME in private or public section of FUN? Or is it okey to declare and define it entirely outside the class with prefix friend.

  • why the errors this above code contain.plz explain .

  • Pathik

    Are all the codes you write now object-oriented programming?

  • tyler

    hey Alex;

    great lessons, and thx for helping me back with the headers files.

    I would like to know how to make my program play music that i have on my computer, and dicplay pictures. when i saw ‘Object Oriented Programing’ thats what i though it was (useing picures in prgramsect…) gut i see that i was wrong. i would like to learn how to make those types of gams that you see on miniclip. ( i know i know, those games are made using flash, but i’m sure you can do simalar thins with C++, like they use C++ for games likie need for speed and the computer version of halo don’t they?)

  • Trevor

    Heya Alex, I really had better start by thanking you for this excellent site. Thanks.

    My question is: is it possible to make only one fuction in a Class A a friend of Class B without making the WHOLE of Class A a friend of Class B. I’ve constructed a crude example to show why I think it can’t be done, perhaps you can tell me if I’m doing something wrong:

    The code above works exactly as expected, but if I replace “friend class manipulate” with “friend int add(number &a,number &b)” or “friend int manipulate::add(number &a,number &b)”, I get compiler errors along the lines of “cannot access private member declared in class ‘number'”.

    Cheers,

    Trevor

    • Alex

      Yes, it is possible, although with a little difficulty.

      I’ve updated the lesson with an example similar to this.

  • asif

    can some one help me with this …..i tried compiling in Gnu G++ environment…and following are the errors…can someone tell me whats wrong with above code!!!111
    friend2.cpp:30: error: invalid use of incomplete type ‘struct two’
    friend2.cpp:5: error: forward declaration of ‘struct two’
    friend2.cpp: In member function ‘int two::accessboth(one)’:
    friend2.cpp:24: error: ‘int one::data1’ is private
    friend2.cpp:55: error: within this context

    • Alex

      Class one needs to see the full declaration of class two for a friend member function to work.

      You have a couple of options here:
      1) Use a friend class instead.
      2) Switch the order of the classes and define the functions outside of the classes (after the declarations).

  • lolo 33

    I’m so lucky to find this websit =)

    thnx so much Alex ,i have c++ exam now

    bye

  • Aki

    Normal friend functions can access private members of other classes.
    But if the friend function is a member function of another class then it cannot access the other class’s private members.

    friends.cpp: In member function ‘int B::boo(A&)’:
    friends.cpp:4:6: error: ‘int A::x’ is private
    friends.cpp:23:9: error: within this context

    • prakash

      // This works.

      #include
      #include

      class A; // forward declaration

      class B
      {
      public:
      int y;
      int boo(A &a) ; // only declare. define later. as friendship has not came in to play yet.

      };

      class A
      {
      int x;
      public:
      friend int B::boo(A &a);
      A()
      {
      x = 5;
      }
      };

      // now we define the function boo which belongs to class B only. just defined outside.
      // if using header files and implementation files separately, it makes crystal clear.

      int B::boo(A &a){
      y = a.x;
      return y;
      }

      int main()
      {
      using namespace std;
      A a;
      B b;
      cout << b.boo(a) << endl;
      }

      • prakash

        Aki,

        you can add more functions in class B, same as foo. i.e. declare first and define later.
        but keep friendship to foo.
        other functions will not have access to private x

        -prakash

  • dinhpq

    Hi Alex,
    I have confused “A friend function may or may not be a member of another class” It mean member function Reset() of class Value may or may not be a friend class Accumulator, is that true? I have an example:

    The compiler error: undefined reference to `Value::Reset(Accumulator&)’
    Can you explain?

    • Alex

      I mean that a friend function may be either a normal function, or a member function of another class.

      In the above code, you’ve declared Reset() as a member of class Value, but you’ve defined Reset to not belong to a class. You will need to fix this, and then you will need to flip the order of the classes around, so class value is declared first (or put it in a header file).

  • samiullah

    Thank U so much Alex;

  • Vaibhav

    Hi Alex,

    Just a question.
    Can a friend function be const or volatile.
    eg. friend void Reset(Accumulator &cAccumulator) const;
    friend volatile void Reset((Accumulator &cAccumulator);

  • Hi, this is an awesome website.
    I learn C++ here much faster than any other places.

    But I just got a little confuse here.
    The friend function, in my opinion, is something like a Getter or Setter.
    Is there any other usage which makes the friend function so important that it needs to be a feature of Cpp?
    Or, what’s the difference between a friend function and a ( normal function + Getter + Setter )

    Thanks 😀
    Ma

    • Danny

      The getters and setters are usually member functions within a class. The setter initializes the data members, and getter can probably display the values set by the setter. For the friend functions, consider a case where you have all your data encapsulated within a class, but there is also a non-class function that needs to access the data in that class. (I used non-class function to clearly set the difference between friend functions and other normal functions)
      How would the non-class function access the data in the class? Making the non-class function a friend to the class by declaring its prototype in the class is the only. Otherwise,trying to access data would give you an error.
      I hope this helps.

  • Enrique

    this website is a jewell for C++ programers. Thanks a lot !

  • anvekar

    Why is it necessary to use an argument in the function prototype inside the class?
    As it is just a prototype, only the argument type should be sufficient right?
    Example: friend void Reset( Accumulator& ); // prototype for the friend function Reset()

    • Alex

      In the above case, the argument is needed because function Reset() is not a member of class Accumulator.

      If Reset() were defined as a member of class Accumulator, then making it a friend would not be necessary, as it would already be able to access the private members of class Accumulator!

  • Quang

    Hello Alex! I want to thank you for what you have done to the programming community! I have a little bit problem about the friend functions:
    - In 8.10 — Const class objects and member functions, you use functions like getDate, getMonth, getYear and i wonder whats the differences between those and friend function ( may be getSomething just for the return !? ) and what is the proper situation to use each of them?
    Thank you for reading this!! Keep up the great work

    • Alex

      Friend functions have direct access to the private data of a class. Non-friend functions have to use public accessor functions (like getMonth()).

      Friend functions are mostly useful for overloading operators, which we talk about in the next chapter. It’s generally good to keep your friend functions to a minimum and use accessors if you can.

  • Mr D

    Hi Alex,

    Regarding the first code example from this lesson:

    If i understand correctly, the reason you’re using a reference (Accumulator &cAccumulator for example) is because there’s also an int main() part that’s implicit, but that you didn’t write out?
    So for example, the whole thing might look something like this?!:

    • Alex

      No, reset is passed in as a reference so that the function can modify the actual Accumulator argument passed in, not a copy of it. If you were to pass cAccumulator by value, you’d end up resetting a copy of the argument, and the original argument would be unchanged. That would defeat the purpose of calling the function. 🙂

      • Danny

        I have read in one of your tutorials that passing by reference saves the overhead that would rather be incurred when passing by value.
        I tried the same program example with passing by value and it works perfectly fine.

        • Alex

          > I have read in one of your tutorials that passing by reference saves the overhead that would rather be incurred when passing by value.

          True.

          > I tried the same program example with passing by value and it works perfectly fine.

          Which example are you referring to?

        • Bassam

          Passing classes by reference is good for performance. see <a href="https://http://www.learncpp.com/cpp-tutorial/73-passing-arguments-by-reference/">Passing arguments by reference</a>

      • Ace

        Alex I’m not getting where is Mr D passing the argument by value! Doesn’t the ‘&’ before the argument name cAccumulator in the function prototype

        indicate passing by reference?

  • Reaversword

    I’ve been trying to get reciprocal "friendship" between two classes. I don’t know if this is nonsense, is just for make the try. But I’m unable to get it working. The only way to get one single class being friend of another one is with this "order":

    1)forward declaration of the friend class (the one able to access the other one’s data)
    2)definition of the class gonna be accessed (the one which accepts friendship)
    3)definition of the friend class.

    If I go out of that structure, it doesn’t works (as swap 2 & 3 steps).

    This is the rule for friendship between classes?.

    A quick example:

    VisualStudio throws the error:

    C2027    use of undefined type ‘Bclass’
    and
    C2228    left of ‘.bVar’ must have class/struct/union

    So, what’s wrong?
    There is a way to get both classes friend of each other?

    • Alex

      The problem here is that the forward declaration tells the compiler about the existence of a class, but nothing about it’s details. So the compiler can’t validate what members the class has.

      The best way to solve this is to move the function definitions out of the class declarations. That way, by the time the compiler compiles them, it will have already seen the class declarations and should know how to resolve all of the names.

      • Reaversword

        Now I understand. Wow!, I was trusting too much in the forward declaration sentence. I really didn’t expect that. Thank you Alex, one more time, brilliant explanation, consecuent solution.

        I leave the code, if somebody wants take a look:

  • JonM

    First I want to thank you on a fantastic tutorial.

    Instead of using Friend class, could one not just get the same result, with just accessing the friend class through getters and setters? And no risk of violating encapsulation would be at risk?

  • Lokesh

    In the "multiple friends" section the setHumidity() and setTemperature() functions used in main() are not defined inside the class definitions.

  • Lokesh

    In first code example in this lesson,

    should be

  • Lokesh

    Quiz 1a. solution - line 20

    should be

  • Meric

    Hmmm. The compiler (g++ with -std=c++0x) kept complaining until I made the following changes to the code given under "Multiple Friends". Any idea why?

  • malt

    On the solution for the 1b) i got this error:
    main.cpp 22:7: error: extra qualification ‘Point3d::’ on member ‘moveByVector’ [-fpermissive]
      void Point3d::moveByVector(Vector3d &v); // so we can use Vector3d here

    I use g++ -std=c++11 main.cpp for compile.

    • Alex

      Oops, my bad. I accidentally left a Point3d:: prefix on moveByVector. Visual Studio didn’t complain about it, so I didn’t notice. The example is fixed now.

  • Bryan

    Thanks for the tutorial.
    I have a question, how to do when Storage and Display classes are in separate files(Storage.h, Storage.cpp, Display.h, Display.cpp)? The compiler shows error: invalid use of incomplete type ‘class Storage’

  • Xhevo

    Hi, Alex

    Typo to line 11 of friend member functions:

    11. void Display::displayItem(Storage &storage);// forward declaration above needed for this declaration line

    should be:
    11. void displayItem(Storage &storage); // forward declaration above needed for this declaration line
                                                                                                 Thanks again!

  • hey , sorry but I forgot in which lesson you told as about the compiler adding *this pointer in the member functions , can u remind me of the lesson please ?

  • Gemparks

    Do you mind clarify a bit further on this sentence: "This is because reset() is not a member function. It does not have a *this pointer"?

    From what i understand, it means that you can’t any assignment on any class member the friend function or class is "befriended with", because it can’t "hold the address of the object the member function was called on"..

    But then, i notice that you can do class member assignment via friend function such as this

    I may have misunderstand the whole thing, therefore what does the aforementioned sentence actually imply?
    This chapter kinda throws me off balance a bit
    Great tutorial though, as always.

    Thanks in advance

    • Alex

      Member functions have an implicit *this pointer that point at the class object that the function can operate on. Non-member functions do not. Full stop.

      Friend functions are given privileges to access or modify the internals (private members) of objects of the friending class, as if they were part of the class. Full stop.

      So in the case of the reset() example, this function is able to access the internals of Accumulator because it is a friend of class Accumulator -- however, because it is a non-member friend, it does not have a *this of type Accumulator to work on. Instead, we’re passing in an Accumulator parameter, and it can work on that (using its friend privileges to set m_value directly).

  • SJ

    Hi Alex,

    First of all great lesson! A lot of information here to absorb but I think I have the idea of friend functions down.

    I tried to implement the quiz by using separate .h and .cpp files for the class declarations and member function definitions, but I ran into a small error. I am getting the error that

    " ‘Point3d’ has not been declared "

    in one of my files, even though I included the necessary header. Below are the files and their contents:

    main.cpp:

    Point3d.h:

    Point3d.cpp:

    Vector3d.h:

    Vector3d.cpp:

    and am receiving the error on the line

    in Vector3d.h

    Can you spot the issue? :\

    • Alex

      Without compiling this to see where the actual error is, I do note that Point3d.h calls Vector3d.h, and Vector3d.h calls Point3d.h. That circular dependency will end in tears, since the header guards will guarantee that one of the headers won’t get the information it needs. Try replacing one of the #includes with a class forward declaration (I think you can forward declare class Vector3d in Point3d.h instead of #including Vector3d.h).

      • SJ

        That was it! Seems so trivial now that you mentioned it. I guess that’s part of the learning process 🙂

        I also forgot to #include <iostream>. Whoops.

  • Shiva

    > However, a better solution would have been to put each class declaration in a separate header file, with the function bodies in corresponding .cpp files.

    Heya Alex, I tried this on the quiz, and like SJ above, found it tricky (solved it with the help of your reply above). It’d be better if you put the proper way to do this in the lesson itself, or even better, as the third quiz question! In case you don’t bother writing it up, here’s my solution, feel free to use it:

    - point3d.h -

    - vector3d.h -

    - point3d.cpp -

    - vector3d.cpp -

    - main.cpp -

    Another thing I noticed, the non-static member initialisation in the quiz solutions is of no use, as you haven’t provided an empty default constructor (which you can’t either, as it would conflict with the current constructor). It’s kind of superfluous, isn’t it? I removed it in my solution.

    One last thing, there’s a typo in:
    > // error: Storage hasn’t see (seen) the full declaration of class Display

    I hope the comment wasn’t too long. 😀

    • Alex

      Good idea. I’ve added a quiz question, with your solution as the answer (with a couple of comment-related tweaks).

      Yes, the non-static member initialization was superfluous. I’ve removed it.

      Thanks for the typo fix!

      • Shiva

        Great! 🙂

        One small thing though: you’ve declared the class member variables in a single line in solutions 1a) and 1b); I believe you adhered to a declare-one-variable-at-a-time rule?

        No big deal, just for the sake of consistency. 😉

        P.S. Just noticed my solution is missing the ‘\’ in the ‘\n’s. (Point3d.cpp & Vector3d.cpp)

        • Alex

          True. With classes it’s a little more common to declare multiple related member variables together, if they’re all the same type, otherwise the class declarations can get a little long sometimes.

          I fixed the missing backslashes. Thanks for noticing!

        • Shiva

          Okay. Got it. Thanks! 🙂

  • Abhay Agarwal

    RESPECTED SIR;

    in EXAMPLE 1 of firend function why you have used ‘&’ sign before accumulator …without that also pragram is working…also u have passobject by value but not reference

    thanks in advance

    • Alex

      It’s a good idea to pass “objects” (non-fundamental data types) by reference instead of by value so you don’t make needless copies (which would still work, but be less performant).

  • Darren

    Better title choices for this chapter?

    "The Friend of my Friend is not my Friend"

    "Friends with benefits"

    "When it hasn’t been your day, your month, or even your year…"

  • Dian Septiana

    Hi Alex,

    Why we need to include point3d.h in main.cpp again, while it’s already included in vector3d.h? I tried to include vector3d.h only in main.cpp, and the program executed without error. I confused, whether I need to re-include point3d or not in main.cpp, because include point3d in main.cpp seems redundant to me, while it’s already include in vector3d.h. CMIIW

    • Alex

      It may be redundant in this particular case, it’s best practice to always directly include all header files that you need in a given code file.

      At the very least, if later vector3d.h is rewritten to not include point3d, your code will still work.

  • Vlad

    Hello Alex

    Concerning the last quiz (and Shiva’s and SJ’s answers), I had the correct result, but then passed over it when codeblocks complained. To spare you the epic, it turned out that the header files needed to be marked for compiling, only, and *not* for linking. Archlinux x64, just in case someone else has the problems.

  • Serafeim

    Hi Alex,

    I think I found a minor typo in the quiz:
    In the quiz description and 1c) solution the z coordinate of the vector in main() is -2.0 (search for Vector3d v(2.0, 2.0, -2.0); ). However in 1a) and 1b) solutions it is -3.0 (search for Vector3d v(2.0, 2.0, -3.0); )

    Also, since this is my first comment, I would like to thank you for these wonderful tutorials.

  • Hannah

    Hi,

    why do I have to use

    class Vector3d; // forward declaration for class Vector3d for function moveByVector()

    in point3d.h? Why can’t I omit the forward declaration and #include "vector3d.h" in point3d.h instead, since vector3d.h contains the Vector3d class definition?

    Thanks!

  • Hannah

    That makes sense. Thank you!

  • Kattencrack Kledge

    On quiz "1c)"
    in main.cpp:

    We don’t need to #include "Point3d.h": Vector3d.h already includes Point3d.h in his file.

    Is including those two in main.cpp is good practice, or is it just redundant to do that?

    • Alex

      It’s good practice. At some point in the future, you may decide that Vector3d shouldn’t include Point3d any more -- and if you do that, then you’ll break all of the programs that were relying on Vector3d to include Point3d.

      It’s best practice to have every file directly include all of the headers it needs to function.

  • Horatio

    In the last question, why the constructors are contained in H file, and other functions in cpp?

  • Nima

    Hello guys.
    Why this code come across with an error?

    I don’t realize why compiler gives an error because I already declare class C in first line(class prototype)
    Please help me.
    Cheers.

    • Alex

      Your declaration of C in the first line is a forward declaration. Forward declarations tell the compiler that an identifier exists, but not anything else about it (e.g. how large it is).

      When you create a class, the compiler needs to know how large objects of that class will be. This means you can’t declare member variables for classes who only have forward declarations.

      In other words, because the compiler doesn’t know how big C is (which is okay), it doesn’t know how big A is (which isn’t okay).

  • chump

    Hi (again) Alex,

    I was wondering if it would be possible for two different classes to have member functions that are friends with the opposite class.
    ie:
    Class A’s member function, Print_B has access to B
    Class B’s member function, Print_A has access to A

    I ask this because when you write the A.h and B.h header files, you will need to #include the other’s .h file to get the full definition of the member function (ie: A.h will have to include B.h to access the definition of Print_A and vice versa). Thus, this creates a circular dependency, if I am not mistaken.

    • Alex

      I don’t think you can do this, as there is no way to remove the cyclic dependency. The best you could do would be to make one of the classes a friend of the other class, which doesn’t require a full class definition.

Leave a Comment

Put C++ code inside [code][/code] tags to use the syntax highlighter