This may be a stupid question so bare with me. Let's say i have a class called "A" that constructs a class called "B". Can class B access functions or variables from class A? I.E:
class A
{
public:
void funcA()
{
B bClass;
bClass.funcB();
}
void otherFunc()
{
cout<<"Test"<<endl;
}
};
class B
{
public:
void funcB()
{
otherFunc();
}
};
int main()
{
class A aClass;
aClass.funcA;
return 0;
}
I have a feeling this wouldn't work, but why? What would be a better way for class B to inform class A that something has happened, without class A polling?
class A
{
public:
void funcA();
void otherFunc()
{
cout<<"Test"<<endl;
}
};
class B
{
public:
void funcB(A* a) // Using class A
{
a->otherFunc();
}
};
void A::funcA()
{
B bClass;
bClass.funcB(this); // Note: provide the this pointer
}
int main()
{
A aClass;
aClass.funcA();
return 0;
}
Hmm ok, the reason I'm asking is because i have threads in both classes, and I'm trying to figure out how to now in class A whether the class B thread has stopped.
In the snippet you provided, you're fine if you define class B first if you use only a pointer to A. You will need a forward declaration of A and move the definition B::functB to your .cpp file.
#include <iostream>
usingnamespace std;
class A; // Forward
class B
{
public:
void funcB(A* a); // Using class A
};
class A
{
public:
void funcA();
void otherFunc()
{
cout << "Test" << endl;
}
};
void A::funcA()
{
B bClass;
bClass.funcB(this); // Note: provide the this pointer
}
void B::funcB(A* a) // Using class A
{
a->otherFunc();
}
int main()
{
A aClass;
aClass.funcA();
return 0;
}
Edit: What I said about declaring B first isn't necessary since the declaration of A doesn't use B. Declaring one forward however does allow you to have A refer to B and B refer to A using pointers.