Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have read existing answers on the two meanings of inline, but I am still confused.

Let's assume we have the following header file:

// myclass.h

#ifndef INCLUDED_MYCLASS
#define INCLUDED_MYCLASS

class MyClass
{
   public:
      void foo(); // declaration
};

inline void MyClass::foo()
{
    // definition
}

#endif

Why does void foo() which is defined outside the class in the file, have to be explicitly defined with inline?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
569 views
Welcome To Ask or Share your Answers For Others

1 Answer

It's because you defined MyClass::foo in a header file. Or a bit more abstract, that definition will be present in multiple translation units (every .cpp file that includes the header).

Having more than one definition of a variable/function in a program is a violation of the one definition rule, which requires that there must be only one definition in a single program of every variable/function.

Note that header guards do not protect against this, as they only protect if you include the same header multiple times in the same file.

Marking the function definition as inline though means that the definition will always be the same across multiple translation units.1.

In practice, this means that the linker will just use the first definition of MyClass::foo and use that everywhere, while ignoring the rest,


1: If this is not the case your program is ill-formed with no diagnostics required whatsoever.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...