Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inline keyword in member function definition

Tags:

c++

Why inline keyword should used in the definition of member function. and Not in declaration?

like image 426
Dew Avatar asked Dec 09 '22 10:12

Dew


2 Answers

inline has some pre-historic use, but nowadays it's best to remember it as saying: "this definition is going to be defined multiple times, and that's okay."

That is, normally the one-definition rule prohibits multiple definitions of a function. This:

// foo.hpp
void foo() { /* body */ }

// a.cpp
#include "foo.hpp"

// b.cpp
#include "foo.hpp"

results in an error, as foo is defined in two translation units. You can declare things as often as you want. This:

// foo.hpp
void foo();

// foo.cpp
void foo()
{
    /* body */
}

// a.cpp
#include "foo.hpp"

// b.cpp
#include "foo.hpp"

is fine, as foo is defined once, and declared multiple times. What inline does is allow this:

// foo.hpp
inline void foo() { /* body */ }

// a.cpp
#include "foo.hpp"

// b.cpp
#include "foo.hpp"

to work. It says "if you see foo more than once, just assume they are the same and be okay with it".

like image 121
GManNickG Avatar answered Dec 22 '22 17:12

GManNickG


No, it can be used in the member function declaration also. Though msdn documentation isn't standard, it is mentioned MSDN inline. See the note part in it.

But, I learnt that it is up to the modern compilers to make a function inline or not despite explicitly mentioning inline.

class foo
{
    inline void methodOne();
};

void foo::methodOne()
{
}

IdeOne Results

Also, one can specify it both declaration and definition to have the same effect.

class foo
{
    inline void methodOne();
};

inline void foo::methodOne()  // Here keyword inline is optional. Needs to be mentioned if method declaration isn't declared inline.
{
}

IdeOne Results

Both of the above will have the same effect.

like image 36
Mahesh Avatar answered Dec 22 '22 17:12

Mahesh