Reputation:
I've always wondered why most codes and tutorial I've read always declare the member functions inside the class and then define it outside like this.
class A{
A doSomething();
};
A A::doSomething(){
//doing something
}
Instead of doing this
class A{
A doSomething(){
//doing something
}
};
Anyway, I was revising my Prof's course and I found this:
"Toute fonction membre définie dans sa classe (dans la déclaration de la classe) est considérée par le compilateur comme une fonction inline. Le mot clé inline n'est plus utilisé."
Which translates into;
"All member functions defined in its class (in the class' declaration) is considered by the compiler as an inline function. The keyword 'inline' is no longer used"
What I understand is abut inline functions is that the work like macros. The compiler copies the entire block of code into every instance that the function is called.
My question is; Is the statement in my Prof's course correct and if yes, what is the reason behind it?
Upvotes: 3
Views: 5037
Reputation: 208323
The keyword inline
does not mean inline in C++, it only means that multiple definitions of exactly the same function can be seen in different translation units that get linked without that being a violation of the One Definition Rule.
With that in mind, member functions defined inside the class definition are implicitly inlined. All translation units that include that header can generate the same symbol, and the linker will discard all but one of them.
Upvotes: 3
Reputation: 258548
Your professor's statement is correct, your understanding of what inline
means is not. An inline
function allows for multiple definitions across translation units, and doesn't necessarily mean that the call is actually inlined (i.e. expanded like a macro).
If you define a free function in a header without inline
or static
and include that header in multiple translation units, you'll break the one definition rule.
Member functions are similar, unless marked as inline (which they implicitly are inside the class definition).
Upvotes: 9