Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ 'class' type redefinition

Tags:

c++

class

I have been attempting to work with classes in c++ for the first time. My circle class and associated header file were working fine, I then moved some files and since then keep getting an error which i have displayed below.

c:\circleobje.cpp(3): error C2011: 'CircleObje' : 'class' type redefinition

c:\circleobje.h(4) : see declaration of 'CircleObje'

CircleObje.h

#ifndef CircleObje_H
#define CircleObje_H
class CircleObje
{
public:
void setCol(float r, float g, float b);
void setCoord(int x, int y);
float getR();
float getG();
float getB();
int getX();
int getY();
};

#endif

CircleObje.cpp

#include "CircleObje.h"

class CircleObje {

float rVal, gVal, bVal;
int xCor, yCor;

public:

void setCol(float r, float g, float b)
{
    rVal = r;
    gVal = g;
    bVal = b;
}

void setCoord(int x, int y)
{
    xCor = x;
    yCor = y;
}

...
};

I haven't copied all of the .cpp functions as I didn't think they were relevant. These files were working without issue before I moved the file locations. Even after renaming them I still have the same error as above. Any ideas to solve the problem?

like image 633
Tom smith Avatar asked Jan 25 '14 17:01

Tom smith


2 Answers

The issue is that you are defining the class twice just as the compiler is telling you. In the cpp you should provide the definitions of the functions like so:

MyClass::MyClass() {
  //my constructor
}

or

void MyClass::foo() {
   //foos implementation
}

so your cpp should look like:

void CirleObje::setCol(float r, float g, float b)
{
    rVal = r;
    gVal = g;
    bVal = b;
}

void CircleObje::setCoord(int x, int y)
{
    xCor = x;
    yCor = y;
}

...

And all the class variables should be defined in the .h file inside of your class.

like image 170
pippin1289 Avatar answered Sep 30 '22 19:09

pippin1289


You have defined the class twice, in the header and in the cpp, so in the .cpp the compiler sees two definitions. Remove the definition of the class on the .cpp.

Class functions should be implemented in the cpp in this way:

<return_type> <class_name>::<function_name>(<function_parameters>)
{
    ...
}

Consider this example class:

//foo.hpp

struct foo
{
    int a;

    void f();
}

The class is implemented in the foo.cpp file:

#include "foo.hpp"

void foo::f()
{
    //Do something...
}
like image 23
Manu343726 Avatar answered Sep 30 '22 19:09

Manu343726