I am throwing myself in the cold blizzard of learning C++. I already know Java but C++ seems odd on certain thing.
Here is the thing : I have a class A and a class B. Class A have an instance of class B inside of itself. Class B needs to be able to call some class A methods so, I put a pointer to class A inside class B’s constructor, and store it inside a variable so I can retrieve these methods with this variable.
Here is my code (simplified) :
ClassA.h
#ifndef CLASSA
#define CLASSA
#include "ParentClass.h"
#include "ClassB.h"
class ClassA : public ParentClass {
private:
ClassB *classB;
public:
ClassA(void);
virtual ~ClassA(void);
};
#endif
ClassA.cpp
#include "ClassA.h"
//-----------------------------------------------------
ClassA::ClassA(void){
classB= new ClassB(this);
}
//-----------------------------------------------------
ClassA::~ClassA(void)
{
}
//-----------------------------------------------------
ClassB.h
#ifndef CLASSB
#define CLASSB
#include "ClassA.h"
class ClassB{
public:
ClassB(ClassA &pClassA){ classA = pClassA; };
ClassA *getClassAInstance(){ return classA; };
private:
ClassA *classA;
};
#endif
ClassB.cpp
#include "ClassA.h"
/*ClassB::ClassB(void){
classA= pClassA;
}*/
Visual Express doesn’t give errors but when I compile, it says that class B doesn’t recognize what is a class A. What the hell ?
1>c:\xxx\xxx\xxx\xxx\xxx\xxx\xxx\xxx\ClassB.h(8): error C2061: syntax
error : identifier ‘ClassA’1>c:\xxx\xxx\xxx\xxx\xxx\xxx\xxx\xxx\ClassB.h(10): error C2143: syntax
error : missing ‘;’ before ‘*’1>c:\xxx\xxx\xxx\xxx\xxx\xxx\xxx\xxx\ClassB.h(10): error C4430:
missing type specifier – int assumed. Note: C++ does not support
default-int1>c:\xxx\xxx\xxx\xxx\xxx\xxx\xxx\xxx\ClassB.h(10): error C4430:
missing type specifier – int assumed. Note: C++ does not support
default-int1>c:\xxx\xxx\xxx\xxx\xxx\xxx\xxx\xxx\ClassB.h(10): warning C4183:
‘getClassAInstance’: missing return type; assumed to be a member
function returning ‘int’1>c:\xxx\xxx\xxx\xxx\xxx\xxx\xxx\xxx\ClassB.h(13): error C2143: syntax
error : missing ‘;’ before ‘*’1>c:\xxx\xxx\xxx\xxx\xxx\xxx\xxx\xxx\ClassB.h(13): error C4430:
missing type specifier – int assumed. Note: C++ does not support
default-int1>c:\xxx\xxx\xxx\xxx\xxx\xxx\xxx\xxx\ClassB.h(13): error C4430:
missing type specifier – int assumed. Note: C++ does not support
default-int1>c:\xxx\xxx\xxx\xxx\xxx\xxx\xxx\xxx\ClassB.h(8): error C2065:
‘classA’ : undeclared identifier1>c:\xxx\xxx\xxx\xxx\xxx\xxx\xxx\xxx\ClassB.h(8): error C2065:
‘pClassA’ : undeclared identifier1>c:\xxx\xxx\xxx\xxx\xxx\xxx\xxx\xxx\ClassB.h(10): error C2065:
‘classA’ : undeclared identifier
Undeclared what ? Returning int ?
undeclared identifier
Why? I included everything, right ? Any ideas what is wrong, guys ?
This is because of a circular reference between your header files. You can break it by forward-declaring one of the classes inside the header of the other, like this: