Home  >  Article  >  Backend Development  >  Can I Define Inline Member Functions in a .cpp File and Still Get Inlining?

Can I Define Inline Member Functions in a .cpp File and Still Get Inlining?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-28 17:34:30311browse

 Can I Define Inline Member Functions in a .cpp File and Still Get Inlining?

Inline Member Function Definition in .cpp File

In C , inline member functions should ideally be defined within the header file to allow the compiler to inline them during compilation. However, certain situations may necessitate placing the implementation outside the header, such as circular dependencies between classes.

In the given example, the class A includes class B, which in turn includes a forward declaration of A. To avoid this circularity, the getA() function of class B is defined in B.cpp. This raises the question: will the compiler still inline getA(), and if so, which definition takes precedence?

As per the C FAQ, the definition of an inline function must be placed in a header file for it to be visible to all source files that use it. Therefore, in this scenario, the compiler will not inline getA(), except when called within B.cpp itself.

Best practice dictates that the inline keyword should only be used once, in the function definition outside the class body. Therefore, any inline keyword placed in the header file is redundant.

Unfortunately, there is no known method to define an inline member function in the .cpp file while still ensuring its inlining by the compiler.

The above is the detailed content of Can I Define Inline Member Functions in a .cpp File and Still Get Inlining?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn