error: Class has not been declared despite header inclusion, and the code compiling fine elsewhere
You seem to be saying that the code you are showing doesn't actually produce the compiler error that you are having a problem with. So we can only guess. Here are some possibilities:
- You could have forgot to include
problemclass.h
from the file where you are usingProblemClass
. - You could have misspelled the name of
ProblemClass
either in its own header file or in the place where you are using it. This can be hard to spot if it is a capitalization error such as writingProblemclass
orproblemClass
instead ofProblemClass
. - You could have copy-pasted your inclusion guard
#defines
from one header file to another and then forgot to change the defined names. Then only the first of those two included header files would take effect. - You could have placed
ProblemClass
in a namespaceA
, in which case you must refer toProblemClass
asA::ProblemClass
if you are referring to it from outside the namespaceA
. - You may be using templates and not expecting two-phase lookup to work the way it does.
- You could have misspelled the file name in your include. The compiler would not report an error on that if you also have an old version of that file under the misspelled name.
- You could have made
ProblemClass
a macro that only gets defined after you includeproblemclass.h
, in which case what you see asProblemClass
gets replaced by something else by the macro preprocessor. - You could have defined
ProblemClass
in a header file other thanproblemclass.h
and thenproblemclass.h
actually defines something else.
I've had that same error message as a result of a circular dependency in my header files / classes:
foo.hpp:
#ifndef FOO_HPP
#define FOO_HPP
#include <stdio.h>
#include "bar.hpp" // <-- here
class Foo {
public:
int value = 0;
void do_foo(Bar myBar) {
printf("foo + %d\n", myBar.value);
}
};
#endif //FOO_HPP
bar.hpp:
#ifndef BAR_HPP
#define BAR_HPP
#include <stdio.h>
#include "foo.hpp" // <-- and here
class Bar {
public:
int value = 1;
void do_bar(Foo myFoo) {
printf("bar = %d \n", myFoo.value);
}
};
#endif //BAR_HPP
Compiling with: g++ -std=c++11 foo.hpp -o foo
resulted in the following output:
In file included from foo.hpp:5:0:
bar.hpp:11:15: error: ‘Foo’ has not been declared
bar.hpp: In member function ‘void Bar::do_bar(int)’:
bar.hpp:12:32: error: request for member ‘value’ in ‘myFoo’, which is of non-class type ‘int’