Reputation: 37
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.
Upvotes: 0
Views: 96
Reputation: 171263
FirstClass(ThirdClass ());
What is this supposed to do?
If the type ThirdClass
has 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 a ThirdClass
, so your constructor argument is (the address of) a function of that type.
If ThirdClass
hasn't been declared (and the error you're getting implies it hasn't been) then it is equivalent to:
FirstClass ThirdClass();
i.e. a (non-constructor) function called ThirdClass
which returns a FirstClass
object.
You probably wanted it to be a constructor taking a ThirdClass
object as the argument, which would be:
FirstClass(ThirdClass);
Or to avoid copying the argument (which is usually what you want):
FirstClass(const ThirdClass&);
Similarly for your Init
function.
The errors saying ThirdClass
is 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 your ThirdClass.h
header, 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
Upvotes: 3
Reputation: 74028
I guess, your constructor and Init()
should be
FirstClass(const ThirdClass &rhs);
...
void Init (const ThirdClass &rhs);
Furthermore, you should consider adding include guards.
Upvotes: 2