I want to use one pointer ( _ref ) to point to different class types. In order to use it, I must cast it to the type that is addressed. I cannot do that because of the incomplete type that is at line 5. If i move the definition of B to line 5, it requires class A to be defined.
#include <iostream>
#include <vector>
#include <string>
class B;
class A{
void *_ref;
std::string _reft;
public:
void setref(A &a){
_ref=&a;
_reft=typeid(a).name();
}
void setref(B &b){
_ref=&b;
_reft=typeid(b).name();
}
void test(){
if(_ref && _reft==std::string(typeid(B).name())){
std::cout<<"Ref to B: ";
static_cast<B*>(_ref)->test(); //error here
}
}
};
class B{
std::vector<A> a;
public:
A A(int i){
return a[i];
}
void test(){
std::cout<<"IT WORKS!";
}
};
int main(){
A a;
B b;
a.setref(b);
a.test();
return 0;
}
Move the implementation of the function that requires
Bto be complete out of the class; put it either in a source file, orinlineafter the definition ofB: