Is function defined in class always inline?
Asked Answered
C

2

5

As per some of the books, function defined(along with definition in header) in class are always inline. Is that true?

How we can create such scenario using test app?

Carlson answered 4/8, 2015 at 14:58 Comment(3)
How we can create such scenario using test app? -- Can you clarify what you mean by that? Obviously you can define a function in a class in a test app. What is the test app testing?Sarmentum
Class functions, (static), are always inline? News to me....Peafowl
@MartinJames what static functions ?Jonijonie
F
8

Functions defined within the class definition are implicitly marked inline.

[C++11: 9.3/2]: A member function may be defined (8.4) in its class definition, in which case it is an inline member function (7.1.2), or it may be defined outside of its class definition if it has already been declared but not defined in its class definition. [..]

That is not the same as saying that they will be inlined.

The inline keyword has implications for storage duration and linkage requirements, and these must be abided by.

[C++11: 7.1.2/2]: A function declaration (8.3.5, 9.3, 11.3) with an inline specifier declares an inline function. The inline specifier indicates to the implementation that inline substitution of the function body at the point of call is to be preferred to the usual function call mechanism. An implementation is not required to perform this inline substitution at the point of call; however, even if this inline substitution is omitted, the other rules for inline functions defined by 7.1.2 shall still be respected.

However, nowadays, your compiler will make the decision on whether to physically inline a function based on its own metrics, not based on the presence or absence of the inline keyword (because, nowadays, frankly the compiler knows best).

I have no idea what "test app" you have in mind, but an example of this in code is very simple:

struct T
{
   void foo() {}  // implicitly `inline`
};
Frow answered 4/8, 2015 at 15:20 Comment(0)
P
3

Yes, it is true, the member functions defined in the class are implicitly declared inline. But inline is only a suggestion you give to the compiler. The compiler could ignore it.

If you want to see what happen with different scenarios you could read the assembler

Primero answered 4/8, 2015 at 15:8 Comment(3)
The keyword inline is not just for inlining. It also tells the compiler that this function can have multiple definitions in different translation units. Are you sure class methods are always declared inline if we consider that property?Verism
The compiler cannot "ignore" the inline keyword. But it will probably not use its presence or absence to determine whether the function gets physically inlined. (Other things will still assuredly happen.)Frow
@Verism Yes we are sureFrow

© 2022 - 2025 — McMap. All rights reserved.