I’m having an issue writing a class as part of a C++ program – in it I have three classes, FirstClass, SecondClass, and ThirdClass – First and Second classes both include ThirdClass.h, and in SecondClass I can declare them normally, however, in FirstClass the first declaration works fine, but any further declarations give me an error that “ThirdClass is not a type name”
here’s a snippet from the class that’s erroring
#include "ThirdClass.h"
class FirstClass
{
public:
FirstClass(void);
// This decleration of ThirdClass works fine
FirstClass(ThirdClass ());
FirstClass(const FirstClass& rhs);
~FirstClass(void);
private:
//These are the two that're erroring
ThirdClass nestedClass();
void Init (ThirdClass ());
void Copy (FirstClass);
};
I’m assuming that it’s something to do with both of them linking to the same header file, but i’ve been looking far and wide trying to find a solution online to no avail.
I did manage to get it working by placing the include inside a namespace, but I also read that this was very bad practice so I don’t really want to do it that way.
What is this supposed to do?
If the type
ThirdClasshas been declared then it declares a constructor that takes the address of a function as its argument, that’s not what you wanted, right?ThirdClass ()is the type of a function that takes no arguments and returns aThirdClass, so your constructor argument is (the address of) a function of that type.If
ThirdClasshasn’t been declared (and the error you’re getting implies it hasn’t been) then it is equivalent to:i.e. a (non-constructor) function called
ThirdClasswhich returns aFirstClassobject.You probably wanted it to be a constructor taking a
ThirdClassobject as the argument, which would be:Or to avoid copying the argument (which is usually what you want):
Similarly for your
Initfunction.The errors saying
ThirdClassis not a type name indicate the type hasn’t been declared. We can only guess because you didn’t show a complete, self-contained example (no cookie for you) but you probably have#include "FirstClass.h"in yourThirdClass.hheader, which causes circular reference and only one of the files is processed correctly.See these questions (and their answers) for more:
cyclic dependency between header files
C++ cyclical header dependency
C++ error: 'Line2' has not been declared