Search code examples
c++headerfriend

where should friend functions be written?


I have two friend functions in a class in a header file

both of them are declared in the class

but the problem is when I write their body in a .cpp file I get this error

undefined reference to...

and when I write the body in the .h file I get this error

multiple definition of..

so I don't understand where should I write the body of friend function?


Solution

  • where should friend functions be written?

    Same as member functions. Either inline in the header, or non-inline in a single translation unit. If inline, it can be outside or inside the class definition. If outside, then it must be declared inline explicitly.

    I get this error

    undefined reference to...

    See this: What is an undefined reference/unresolved external symbol error and how do I fix it?

    and when I write the body in the .h file I get this error

    multiple definition of..

    This means that you failed to declare the function as inline, and consequently failed to follow the One Definition Rule. Solution is to declare the function inline.