Jimmy Lu
Jimmy Lu

Reputation: 5100

Does Inline restrict the function/method to the scope of its current source file?

Say I have something the following in my program,

// namespaceB.h
#include "namespaceA.h"
namespace B {
class Tree {
    public:
    Tree *prev;
    Tree *next;
    Tree *down;
    A::Kind kind;

    Tree();
    ~Tree();
};
}
// end of namespaceB.h
// Implementation details of the class are placed in namespaceB.cc
// Constructor / Desctructor defined in the namespaceB.cc file!
// Something like this,
#include "namespaceB.h"
namespace B {
inline Tree::Tree() { ... }
inline Tree::~Tree() { ... }
}

My question is that does inlining the ctor/dtor restrict their uses to within the current source file?

I thought inlining is just a way to improve efficiency?

What if Tree has a memeber method like

Tree& Tree::operator+(Tree const& rhs);

defined in header file, and in the source file

inline Tree& Tree::operator+(Tree const& rhs) { ... }

I played with that a bit, and it seems "inline" here also restricts Tree::operator+(...) to the scope of that source file

which means this will fail:

#include "namespaceB.h"
int main() {
B::Tree tree;    // Fail to link
return 0;    
}

As shown here: Cannot create an instance of a class from another namespace?

After I removed "inline" from ctor/dtor of class Tree, everything compiled and linked perfectly.

Can someone please explain what exactly inline does?

Thanks,

Upvotes: 1

Views: 300

Answers (1)

JoeG
JoeG

Reputation: 13192

If you mark a function as inline, you must include it in every source file from which it is used.

The C++11 standard has this to say:

7.1.2/4: "An inline function shall be defined in every translation unit in which it is odr-used and shall have exactly the same definition in every case."

Upvotes: 2

Related Questions