techydesigner techydesigner - 1 month ago 28
C++ Question

C++ error: redefinition of class

Note: I have searched thoroughly on SO and the solutions posted for other's with similar questions are not working for me here.

I am writing my own custom 'string-like' class in C++, and am encoutering the following errors when compiling:


./PyString.h:8:11: error: out-of-line declaration of 'PyString' does
not match any declaration in 'PyString' PyString::PyString (char*);
^

./PyString.h:9:11: error: definition of implicitly declared destructor PyString::~PyString (void);

pystring.cpp:4:7: error: redefinition of 'PyString' class PyString {


As for the first and second errors, moving around the destructor into the class definition itself in the
cpp
file did not work.

As for the third error, I can't seem to fix it - I'm not redefining the class!

Here is
pystring.h
:

#ifndef PYSTRING_INCLUDED
#define PYSTRING_INCLUDED

class PyString {
char* string;
};

PyString::PyString (char*);
PyString::~PyString (void);

#endif


Here is
pystring.cpp
:

#include "PyString.h"
#define NULL 0

class PyString {
char* string = NULL;
public:
PyString(char inString) {
string = new char[inString];
};

~PyString(void) {
delete string;
};
};


For reference, here is the compile output as a screenshot:
Compiler output screenshot

Any help is greatly appreciated.

Answer

You're defining your class PyString in your header AND in your cpp file, and also, a function definition doesn't need a ; at it's end.
And... your function prototypes needs to be in your class declaration in your header :

pystring.h

class PyString {
public: //ALWAYS indicate what is public/private/protected in your class
    PyString (char* inString);
    ~PyString (); // Don't put void when there's no parameter

private: // All attributes are private
    char* string;
};

pystring.cpp

#include "PyString.h"

PyString::PyString(char* inString) {
    string = inString; // Avoid using new unless you're forced to
}

PyString::~PyString() {
}