3

Are member functions defined in a class definition compiled differently than member functions defined elsewhere in C++? For example, consider the following foo.h

#pragma once struct foo { void bar() {} void buz(); }; 

and foo.cpp

#include "foo.h" void foo::buz() {}; 

If we look at the symbols for foo.o

$ g++ -c foo.cpp $ nm -a foo.o 0000000000000000 b .bss 0000000000000000 n .comment 0000000000000000 d .data 0000000000000000 r .eh_frame 0000000000000000 a foo.cpp 0000000000000000 n .note.GNU-stack 0000000000000000 t .text 0000000000000000 T _ZN3foo3buzEv $ c++filt _ZN3foo3buzEv foo::buz() 

we see that we only have a symbol for foo::buz. Now, say that we compile multiple files that all include foo.h and then create a library from the result. Are the member functions bar and buz treated differently?

1
  • Try compiling the same thing again, but make use of the inline member function. Commented Jun 5, 2016 at 5:52

2 Answers 2

2

Yes, there is a difference. If a member function is defined inside class definition then the compiler tries to make it an inline function. For your example, the function is simple enough to make it inline. So the compiler has made bar inline and you only see symbol of baz.

Whether it will be good or bad depends largely on the specific functions and your use case. Inline function do not need an actual function call, the there is a performance improvement there. But the downside is if you include the class header in many places then that will increase the binary size.

Also note that inline is a request to the compiler. The compiler is free to ignore the request and treat it a normal method.

Sign up to request clarification or add additional context in comments.

1 Comment

Inline member functions may also lead to unnecessary recompilation. Anything that includes the header file needs to be recompiled on any edit, whereas if the change is located in a C++ source file, only that file needs recompiling (and everything that uses it re-linked, which is not as expensive).
1

As from 9.2.1/1:

A member function may be defined in its class definition, in which case it is an inline member function

On the other side, from 9.2.1/2:

An inline member function (whether static or non-static) may also be defined outside of its class definition provided either its declaration in the class definition or its definition outside of the class definition declares the function as inline orconstexpr.

The question was: Are member functions defined in a class definition compiled differently than member functions defined elsewhere in C++?

It mostly depends on how you define them, as you can deduce from the citations above.
In your example, they are actually different.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.