I am trying to share info between classes using information from here,
except that I am not able to get these two classes to compile and thus to
communicate with each other.
So, what I want is for ClassB to get a reference to ClassA, and
ClassB to be initialized in ClassA.
Compiler errors (using g++):
In member function
'void ClassA::foo()':
hello.cpp:9: error:'ClassB'was not declared in this scope
hello.cpp:9: error:'someB'was not declared in this scope
hello.cpp:9: error: expected type-specifier before'ClassB'
hello.cpp:9: error: expected';'before'ClassB'
So then I try adding class ClassB; before ClassA,
like:
class ClassB; // just this here.
class ClassA; // all of classA here.
class ClassB; // all of classB here.
And I get:
hello.cpp: In member function ‘void ClassA::foo()’:
hello.cpp:11: error: invalid use of incomplete type ‘struct ClassB’
hello.cpp:3: error: forward declaration of ‘struct ClassB’
hello.cpp:12: error: invalid use of incomplete type ‘struct ClassB’
hello.cpp:3: error: forward declaration of ‘struct ClassB’
This is the code that am I trying to use based on the website above:
include stdio.h
class ClassA {
public:
void foo() {
ClassB *someB = new ClassB();
someB->setRelative(this);
}
void bar() {
printf("B is communicating with me =)\n");
}
};
class ClassB {
ClassA *m_relative;
public:
void setRelative(ClassA *other) {
this->m_relative = other;
}
void foo() {
m_relative->bar();
}
};
You’re obviously having a circular dependency here, something you can’t really solve using headers only (might be possible with some macro tricks, but I wouldn’t worry about).
What you should do is splitting your code into declarations (headers) and implementations.
a.h
a.cpp
b.h
b.cpp