views:

76

answers:

4

Apologies for the code dump:

gameObject.cpp:

#include "gameObject.h"
class gameObject
{
    private:
    int x;
    int y;
    public:
    gameObject()
    {
    x = 0;
    y = 0;
    }

    gameObject(int inx, int iny)
    {
        x = inx;
        y = iny;
    }

    ~gameObject()
    {
    //
    }
    int add()
    {
        return x+y;
    }

};

gameObject.h:

class gameObject
{
    private:
    int x;
    int y;
    public:
    gameObject();

    gameObject(int inx, int iny);
    ~gameObject();
    int add();
};

Errors:

||=== terrac, Debug ===|
C:\terrac\gameObject.cpp|4|error: redefinition of `class gameObject'|
C:\terrac\gameObject.h|3|error: previous definition of `class gameObject'|
||=== Build finished: 2 errors, 0 warnings ===|

I can't figure out what's wrong. Help?

+4  A: 

You're defining the class in the header file, include the header file into a *.cpp file and define the class a second time because the first definition is dragged into the translation unit by the header file. But only one gameObject class definition is allowed per translation unit.

You actually don't need to define the class a second time just to implement the functions. Implement the functions like this:

#include "gameObject.h"

gameObject::gameObject(int inx, int iny)
{
    x = inx;
    y = iny;
}

int gameObject::add()
{
    return x+y;
}

etc

sellibitze
Ahhhh, thank you!
Dataflashsabot
+4  A: 

the implementation in the cpp file should be in the form

gameObject::gameObject()
    {
    x = 0;
    y = 0;
    }
gameObject::gameObject(int inx, int iny)
    {
        x = inx;
        y = iny;
    }

gameObject::~gameObject()
    {
    //
    }
int gameObject::add()
    {
        return x+y;
    }

not within a class gameObject { } definition block

frag
In addition to this fix, constructors should use *ctor-initializer-list* and not the body of the constructor to initialize member variables.
Ben Voigt
absolutely agree (though not related to the question)(+1 from me)
frag
A: 

You define the class gameObject in both your .cpp file and your .h file.
That is creating a redefinition error.

You should define the class, ONCE, in ONE place. (convention says the definition is in the .h, and all the implementation is in the .cpp)

Please help us understand better, what part of the error message did you have trouble with?

The first part of the error says the class has been redefined in gameObject.cpp
The second part of the error says the previous definition is in gameObject.h.

How much clearer could the message be?

abelenky
+1  A: 

You're defining the same class twice is why.

If your intent is to implement the methods in the CPP file then do so something like this:

gameObject::gameObject()
{
    x = 0;
    y = 0;
}
gameObject::~gameObject()
{
    //
}
int gameObject::add()
{
        return x+y;
}
locka