sud03r
sud03r

Reputation: 19759

Inlined constructors? Explain this behavior[C++]

Consider this code

#include <iostream> 
#include <cstdio>
using namespace std;

class Dummy {
public:
    Dummy();
};

inline Dummy::Dummy() {
    printf("Wow! :Dummy rocks\n");
}

int main() {
    Dummy d;
}

All is good here!

Now I do this modification. I move the declaration of Dummy to "dummy.h".

class Dummy {
public:
    Dummy();
};

And define the constructor Dummy() as following in "dummy.cpp"

#include "dummy.h"
inline Dummy::Dummy() {
    printf("Wow! :Dummy rocks\n");
}

And finally, I have my main file as:

#include <iostream> 
#include <cstdio>
#include "dummy.h"
using namespace std;

int main() {
    Dummy d;
}

It compiles fine, but I get a linker error complaining an undefined reference to Dummy::Dummy().

Any insights.

--

Upvotes: 0

Views: 261

Answers (3)

LmSNe
LmSNe

Reputation: 143

You should think how compiling works at C++ and the idea of separate compiling units used at C++ and encapsulation gained using headers and cpp files.

Look here: http://www.parashift.com/c++-faq-lite/inline-functions.html#faq-9.6

The inline tells the complier that instead of calling the function to "copy - paste" its code at the place of the function call. When you put the inline definition in a CPP file it won't be visible during linking to other compiled units (its in cpp file not in h file) so the compiler understand from the signature placed at the class that there is no-paramter Con's so it won't implement the default one. But the linker can't find the function body cause it is implemnted inline at the cpp file.

Upvotes: 2

slacker
slacker

Reputation: 2142

You have to put all inline functions (including methods and constructors/destructors) in a header file, where they are declared.

Though this code should work either way, with main() calling the constructor as if the inline keyword was not there. Are you sure you are passing object files from both compilation units to the linker?

Upvotes: 3

nathan
nathan

Reputation: 5733

Try removing the inline specifier from the your implementation file. If my understanding is correct, you can only inline in a header

Upvotes: 0

Related Questions