Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
626 views
in Technique[技术] by (71.8m points)

c++ - Why do class member functions defined outside the class (but in header file) have to be inlined?

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...