I want to include implementation of a function inside an .h file.
I know I would rather separate declaration and implementation to .h and .c file accordingly, this is not a part of my question.
When I implement the function inside the class, I receive no errors:
class Foo
{
public:
// Class constructor
Foo() { }
};
When I implement the function outside the class (still in the .h file):
class Foo
{
public:
// Class constructor
Foo();
};
Foo::Foo()
{
}
I receive the following error:
multiple definition of Foo:Foo()
Can someone explain me the logic behind this? Thanks.
This is because when you define the function in the class definition, the method is treated as an inline
function. Which can be included in multiple source files, be compiled and linked together and still have the linker not complain about multiple definitions.
But when you define the constructor outside the class, #include
it in multiple source files, compile them together and then link them. You get multiple definitions for the same function.
Remember that #include
ing a file is essentially a copy paste of that file into the file that #include
s it. So every time that file is included, you get a definition for the function in that source file. And then when you compile and link multiple such sources together you get multiple definitions for the same non-inline function.
For more see on inline
, see http://en.cppreference.com/w/cpp/language/inline. The examples section has a good chunk of code that should help.
You can also explicitly mark the definition outside the class to be inline
like @StoryTeller correctly noted.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With