0

I have created a small interface for objects that can be represented in text mode using the operator<< like so:

// ICliObject.h

class ICliObject
{
public:

    ~ICliObject() = default;
    friend std::ostream& operator<<(std::ostream& p_stream, const ICliObject& p_cliUiObject);


protected:
    virtual void print(std::ostream& p_stream) const = 0;

};


std::ostream& operator<<(std::ostream& p_stream, const ICliObject& p_cliUiObject)
{
    p_cliUiObject.print(p_stream);

    return p_stream;
}

When I inherit from this interface and try to build, the compilation works but I get the following linking error: In blablabla.cpp: multiple definition of operator<<(std::ostream& p_stream, const ICliObject& p_cliUiObject)

In all derived classes, I have took care of not re-defining/declaring the operator. The only way I can solve my problem is in inlining the operator in ICliObject.h. What is going on?

Note: I use GCC on Ubuntu.

BobMorane
  • 3,870
  • 3
  • 20
  • 42

1 Answers1

3

This has nothing to do with friend or with operator<< or with inheritance.

Like any function (or object) defined at namespace scope, if you do so multiple times in your program (including by having it in a header file that you #include in multiple translation units), you will get this error.

And, like in all those other cases, the solution is to either move the implementation to a "source file", or stick the inline keyword on it (which you already suggested, but it's literally the solution so I don't know why it's not acceptable).

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
  • Another possible solution would be to define the function inside the class definition (because that makes it implicitly `inline`) – M.M Jun 08 '17 at 23:12
  • So the definition I added outside the class (but in the same header file) for `operator<<` made it defined multiple times across the program, which caused the linking error. I get it, thanks. – BobMorane Jun 08 '17 at 23:45