If I have classes A and B, how can I create a reference to B inside of A? I read that you need use a pointer or a reference, but I can’t find out more than that. Here’s an example of what I’m talking about:
class B;
class A {
public:
B * b_pointer;
void setSelf(B * given_b_pointer) {
b_pointer = given_b_pointer;
};
void printBName() {
print (b_pointer.my_name);
};
};
class B {
public:
string my_name;
void setSelf(string my_given_name) {
my_name = my_given_name;
};
}
This gives me several errors. What am I doing wrong, and how can I fix it?
EDIT: The relevant error message:
error: request for member ‘my_name’ in ‘((B*)this)->A::b_pointer’, which
is of non-class type ‘B*’.
Error message slightly edited to replace actual class names with psuedo-class names.
[Updated] You need to forward declare class B and you can not use any of B’s members in the class until it has been declared so move the declaration of
printBNameto the code file.