tags:

views:

79

answers:

3

Basically I have code which looks like this inside a header file:

class Bar;
class Foo
{
public:
   Bar GetBar();
};

class Bar
{
    Foo CreateFoo() {}
};

Bar Foo::GetBar()
{...}

The problem with this code is that as soon as the header is included in more then one file the linker will complain that there are multiple definitions of Foo::GetBar. However I can't put it inside the class definition where that would work, because Bar isn't defined at that point. I don't want to put it inside a seperate .cpp file, because the rest of the library I'm writing (which isn't that heavy weight anyway) is mostly templates I would have to place in a header anyway and it seems a bit anoying to require linking something else in only because I had to put one function outside the header.

So is there anyway to solve this problem without creating another .cpp file?

+8  A: 
inline Bar Foo::GetBar()
{...}
moonshadow
One question though, since `inline` is basically a hint to the compiler, but does not actually force the compiler to inline the function, does this still works if the compiler decides not to inline it ?
Matthieu M.
@Matthieu: it also gives the function "inline linkage", which basically means you're allowed multiple definitions (as long as they're all the same).
Mike Seymour
A: 

You can declare this Foo::GetBar() function inline. I should solve the multiple definitions.

Didier Trosset
A: 

Make the function explicitly inline:

inline Bar Foo::GetBar()
{...}
anon