Hi!, this is my first post in the forum and it's sad it's not an answer but a question, well... I'm starting with c++.
My problem is that I have two cross referenced classes, A and B. A has a pointer B *myb and B has a pointer A* mya, the constructor of the class B need a pointer to an A-object.
I want to call an A-function using the pointer mya in B, there's no problem if I call the function from the outside of the B class, let's say in the main(). But if I call the function from inside the B class, let's say mya-> theFunction() inside a B-function, the compiler kick me off.
In the sample code bellow I have the clases defined in diferent files (to simulate the real programing enviroment), there is an A class and a B class, both with the cross referenced pointer and with the A-function void A::sayHello() to be executed from B. You can see that if you compile the code it wouldn't give any problem, but uncommenting the line //mya->sayHello() in b.cpp the compiler complains.
I need to know why is this happening and how can I solve it, I know it could be because of my ignorance or bad pointer manipulation.
Thanks :)
=================== fileneame: a.h ======================
1 2 3 4 5 6 7 8 9
|
#ifndef _A_H_
#define _A_H_
class B;
class A{
public:
B *myb;
void sayHello();
};
#endif //_A_H_
|
================== filename: a.cpp ======================
1 2 3 4 5
|
#include "a.h"
#include <iostream>
void A::sayHello(){
std::cout<< "Hello from A inside B" << std::endl;
}
|
=================== filename: b.h =======================
1 2 3 4 5 6 7 8 9 10 11
|
#ifndef _B_H_
#define _B_H_
class A;
class B{
public:
B(A *aa);
void sayBye();
A *mya;
};
#endif //_B_H_
|
=================== filename: b.cpp =====================
1 2 3 4 5 6 7 8 9 10 11
|
#include "b.h"
#include <iostream>
B::B(A *aa){
mya = aa;
}
void B::sayBye()
// Here is the problem, uncommenting the line bellow
// the compiler kick me off
//mya->sayHello();
}
|
=================== filename: main.cpp ==================
1 2 3 4 5 6 7 8 9 10 11
|
#include "a.h"
#include "b.h"
int main(){
A aaa;
A * a = &aaa;
B bbb(a);
bbb.mya->sayHello();
//I would like to use bbb.sayBye() insted the above line :(
return 0;
}
|