Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementation Inside a Declaration C++ [duplicate]

Tags:

c++

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.

like image 632
Noa Yehezkel Avatar asked Jun 27 '17 07:06

Noa Yehezkel


1 Answers

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 #includeing a file is essentially a copy paste of that file into the file that #includes 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.

like image 112
Curious Avatar answered Oct 02 '22 22:10

Curious