Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is "inline" implicit in C++ member functions defined in class definition

Tags:

c++

class

inline

According to the C++ specification, are the following two classes equivalently defined?

class A {    void f()    {    } };  class B {    inline void f()    {    } }; 

i.e., is putting the "inline" qualifier on such member function defined in the class definition completely redundant?

Followon question: Assuming it is redundant, for code style, would it be sensible to keep the "inline" tag, so a future developer realises that function should be inlined, and does not remove the definition somewhere else and remove the inlining?

Thanks :)

like image 397
Sam Avatar asked Feb 08 '12 11:02

Sam


People also ask

How is inline member function defined?

A member function that is defined inside its class member list is called an inline member function. Member functions containing a few lines of code are usually declared inline. In the above example, add() is an inline member function.

Where are inline functions defined?

An inline function is one for which the compiler copies the code from the function definition directly into the code of the calling function rather than creating a separate set of instructions in memory. This eliminates call-linkage overhead and can expose significant optimization opportunities.

Are member functions inline by default?

For class members, the default is the opposite: if you just declare them, they will not be inlined. If you define them, they will be inline. And if myclass::fn2() definition goes into a proper source, must lose the inline keyword.

How would you define member function as inline out side of the class?

If a member function's definition is outside the class declaration, it is treated as an inline function only if it is explicitly declared as inline . In addition, the function name in the definition must be qualified with its class name using the scope-resolution operator ( :: ).


1 Answers

The C++ ISO standard says:

A function defined within a class definition is an inline function.

But, this doesn't mean the function will necessarily be inlined: generally nowadays, it appears that the compiler will decide if inlining the function will lead to any benefits.

like image 53
craigmj Avatar answered Oct 09 '22 02:10

craigmj