Inline keyword in member function definition

Why the inline keyword should be used in the definition of a member function. and not in the declaration?

+3
source share
3 answers

inline has some prehistoric use, but at the moment it’s best to remember it: “this definition will be defined several times, and that’s good.”

That is, as a rule, the rule of one definition prohibits several definitions of a function. It:

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

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

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

leads to an error, because it foois defined in two translation units. You can declare things as often as you want. It:

// foo.hpp
void foo();

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

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

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

excellent, because it foois defined once and declared several times. What allows inline:

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

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

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

. : " foo , , ".

+10

, -. msdn , MSDN. . .

, , .

class foo
{
    inline void methodOne();
};

void foo::methodOne()
{
}

IdeOne

, , , .

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

.

+3

This is because it is simply the key to the compiler to place the body of the function directly in the place where it is called. Therefore, it makes sense for the compiler to look at the place where the function is defined. Therefore, if you perform nesting functions, you must put the actual function code in the class header file, if you do not, you may get linker errors.

If you want to know more about inlining, see: http://www.parashift.com/c++-faq-lite/inline-functions.html

+1
source

Source: https://habr.com/ru/post/1795013/


All Articles