Search code examples
c++member-functionsduplicate-symbol

C++ member function definition outside the class | duplicate symbols


In one of my classes header file Lfo.h, I have a class definition where I put the member function definition out of the class (It might be better to have a separate .cpp file but it should be ok put here?):

// Lfo.h
class CLfo
{
public:
    static int create (CLfo*& pCLfo);
};

int CLfo::create(CLfo *&pCLfo)
{
    pCLfo = new CLfo;
    return 0;
}

Then I have another class called CVibrato:

// Vibrato.h
class CVibrato
{
public:
    static int create (CVibrato*& pCVibrato);
private:
    CVibrato();
};

and the .cpp file (in the cpp file, I include Lfo.h because later on the vibrato class will have a lfo member but I haven't implemented right now):

// Vibrato.cpp
#include "Lfo.h"
#include "Vibrato.h"
int CVibrato::create(CVibrato *&pCVibrato)
{
    pCVibrato = new CVibrato();
    return 0;

}

CVibrato::CVibrato()
{
}

Then I want to create a instance of vibrato class in main()

#include "Vibrato.h"
#include "Lfo.h"   // if comment this line out there will be no error, why is that?

int main()
{
    CVibrato *vibrato = 0;
    CVibrato::create(vibrato);
    return 0;
}

However I get a 1 duplicate symbol for architecture x86_64 error. What is duplicated? It seems the reason is in Lfo.h, I put the definition of the member function outside of the class, if I put it inside, the program runs properly. But I cannot understand. In c++, aren't we allowed to do this? By the way, if one of my class (in my case vibrato) is going to have a class member of another class (in this case lfo), should I include the header file of member class in .h (vibrato.h) file or .cpp (vibrato.cpp) file?


Solution

  • Classes are declarations. No code is produced from a declaration. Even if you have a member function in the class, it is treated as if an inline by the compiler. Function bodies can be put in a header but should always be declared as inline. The compiler may not actually inline it, but it will treat it as a single instance for code creation.

    Any time you:

    void function( ) { }
    

    Code is created for that function. If a header is included more than once the compiler is told to create the code more than once. But all functions must have unique names! So you get the duplicate error. That is why code generating lines belong in the .cpp files.

    'inline' tells the compiler not to create immediate code but to create the code at the usage point.