I know that inline member functions by definition should go into the header. But what if it's not possible to put the implementation of the function into the header? Let's take this situation:
File A.h
#pragma once #include "B.h" class A{ B b; };
File B.h
#pragma once class A; //forward declaration class B{ inline A getA(); };
Due to the circular include I have to put the implementation of getA
into
B.cpp
#include "B.h" #include "A.h" inline A B::getA(){ return A(); }
Will the compiler inline getA
? If so, which inline keyword is the significant one (the one in the header or the one in the .cpp file)? Is there another way to put the definition of an inline member function into its .cpp file?
Yes, you are right. If I put the inline method definition in a . cpp file I'll get an "unresolved external" error from the linker. So whether explicit or implicit, the inline functions has to be in the header.
Advertisements. C++ inline function is powerful concept that is commonly used with classes. If a function is inline, the compiler places a copy of the code of that function at each point where the function is called at compile time.
Inline function is a function that is expanded in line when it is called. When the inline function is called whole code of the inline function gets inserted or substituted at the point of inline function call. This substitution is performed by the C++ compiler at compile time.
An equivalent way to declare an inline member function is to either declare it in the class with the inline keyword (and define the function outside of its class) or to define it outside of the class declaration using the inline keyword.
Quoting from C++ FAQ:
Note: It's imperative that the function's definition (the part between the {...}) be placed in a header file, unless the function is used only in a single .cpp file. In particular, if you put the inline function's definition into a .cpp file and you call it from some other .cpp file, you'll get an "unresolved external" error from the linker.
The compiler need to see the definition of the inline function whenever it finds any use of that inline function. That is typically possible if the inline function is placed in a header file.
Will the compiler inline getA?
No, except when the the use of getA()
is in B.cpp itself.
If so, which inline keyword is the significant one (the one in the header or the one in the cpp)?
Best practice: only in the definition outside the class body.
Is there another way to put the definition of an inline member function into it's cpp file?
No, at least I don't know.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With