Home > Backend Development > C++ > Can You Inline Member Functions Defined in .cpp Files?

Can You Inline Member Functions Defined in .cpp Files?

DDD
Release: 2024-10-27 22:25:02
Original
464 people have browsed it

 Can You Inline Member Functions Defined in .cpp Files?

Placing Inline Member Function Definition in .cpp File

In this article, we will address the dilemma of implementing inline member functions in .cpp files despite the convention of placing them in headers.

The issue arises from circular inclusion, as demonstrated by the code snippets below:

<code class="cpp">// File A.h
#include "B.h"

class A {
    B b;
};</code>
Copy after login
<code class="cpp">// File B.h
#include "A.h" // forward declaration

class B {
    inline A getA();
};</code>
Copy after login

Due to the circular dependency, the implementation of getA() must be placed in B.cpp:

<code class="cpp">// File B.cpp
#include "B.h"
#include "A.h"

inline A B::getA() {
    return A();
}</code>
Copy after login

Will the Compiler Inline getA?

No, unless the use of getA() is within B.cpp itself.

Significance of Inline Keywords

The inline keyword in the definition outside the class body is most significant.

Alternative Ways to Define Inline Member Functions in .cpp Files

Unfortunately, there is no alternative approach to placing the definition of an inline member function in its .cpp file. The standard requires the compiler to see the function definition wherever it is called.

The above is the detailed content of Can You Inline Member Functions Defined in .cpp Files?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template