Home > Backend Development > C++ > body text

Can You Define Inline Member Functions in .cpp Files? A Look at Circular Includes and Compiler Behavior.

Susan Sarandon
Release: 2024-10-30 14:03:52
Original
460 people have browsed it

 Can You Define Inline Member Functions in .cpp Files? A Look at Circular Includes and Compiler Behavior.

Defining Inline Member Functions in .cpp Files: A Conundrum

While inline member functions are typically placed in headers for direct inclusion during compilation, certain scenarios demand their implementation in .cpp files. One such case involves circular includes, where the implementation of an inline member function must be defined in a .cpp file.

Dilemma of Circular Includes

Consider the following example:

A.h

<code class="cpp">#pragma once
#include "B.h"

class A {
    B b;
};</code>
Copy after login

B.h

<code class="cpp">#pragma once
class A; // forward declaration

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

B.cpp

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

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

In this situation, due to the circular include between A.h and B.h, the implementation of the inline member function getA() needs to be defined in B.cpp. However, this raises a fundamental question:

Will the Compiler Inline getA() Properly?

No. The compiler only inlines a function when its definition is available at the point of use. In the above example, the definition of getA() is not visible when it is called from other .cpp files, leading to an "unresolved external" error during linking.

Significance of Inline Keywords

Only the inline keyword present in the definition outside the class body (in B.cpp in this case) is significant. The inline keyword in the header (in B.h) serves as a declaration, indicating that the implementation will be provided elsewhere.

Alternative Approach to Defining Inline Member Functions in .cpp Files

Currently, there is no alternative method to define inline member functions in .cpp files. The standard requires that their definition be placed in headers for proper inline expansion.

The above is the detailed content of Can You Define Inline Member Functions in .cpp Files? A Look at Circular Includes and Compiler Behavior.. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!