Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between inline member function and normal member function?

Tags:

c++

Is there any difference between inline member function (function body inline) and other normal member function (function body in a separate .cpp file)?

for example,

class A
{
  void member(){}
};

and

// Header file (.hpp)

class B
{
  void member();
};

// Implementation file (.cpp)

void B::member(){}
like image 866
Thomson Avatar asked Dec 12 '22 16:12

Thomson


1 Answers

There is absolutely no difference.

The only difference between the two is that the member inside the class is implicitly tagged as inline. But this has no real meaning.

See: inline and good practices

The documentation says that the inline tag is a hint to the compiler (by the developer) that a method should be inlined. All modern compilers ignore this hint and use there own internal heuristic to determine when a method should be inlined (As humans are notoriously bad and making this decision).

The other use of inline is that it tells the linker that it may expect to see multiple definitions of a method. When the function definition is in the header file each compilation unit that gets the header file will have a definition of the function (assuming it is not inlined). Normally this would cause the linker to generate errors. With the inline tag the compiler understands why there are multiple definitions and will remove all but one from the application.

Note on inlining the processes: A method does not need to be in the header file to inlined. Modern compilers have a processes a full application optimization where all functions can be considered for inlining even if they have been compiled in different compilation units. Since the inline flag is generally ignored it make no difference if you put the method in the header or the source file.

like image 136
Martin York Avatar answered May 30 '23 04:05

Martin York