Reputation: 3446
I'm trying to do a barebones example of a class A that provides callback methods to a dependent class B by passing a reference to itself. The best I've produced is the following:
#ifndef A_H
#define A_H
#include "b.h"
namespace b {
class ClassB;
}
namespace a {
class ClassA {
public:
ClassA();
b::ClassB* m_b;
void callback(const std::string& msg);
};
}
#endif
#include "a.h"
a::ClassA::ClassA() {
m_b = new b::ClassB(this);
}
void a::ClassA::callback(const std::string& msg) {
std::cout << msg << '\n';
}
int main(void)
{
a::ClassA* doit = new a::ClassA();
delete doit;
return 0;
}
#ifndef B_H
#define B_H
#include <iostream>
#include <string>
namespace a {
class ClassA;
}
namespace b {
class ClassB{
public:
ClassB(a::ClassA* a_inst);
};
}
#endif
#include "b.h"
namespace b {
ClassB::ClassB(a::ClassA* a_inst) {
a_inst->callback("Call me maybe");
}
}
This is the closest I can get to a compilation, but I'm left with the following errors:
b.cc: In constructor 'b::ClassB::ClassB(a::ClassA*)':
b.cc:6:9: error: invalid use of incomplete type 'struct a::ClassA'
b.h:8:8: error: forward declaration of 'struct a::ClassA'
How can I fix this? And is there a better way to construct this relationship?
Upvotes: 1
Views: 382
Reputation: 3389
In your file b.cc
, you must include a.h
.
In the .h file you can't because of multiple inclusion but since .cc
files are not included, they can include whatever they want.
Note :
You should not forward declare b in your a.h
file because it is declared in b.h
and you included it.
You could also, as stated @chris, remove the #include "b.h"
in your a.h
and put it in your a.cc
.
Upvotes: 1