I have an (for C++ programmers better than me) simple problem with classes and pointers. I thought about posting example code describing my problem but I found it easier to just explain it in words.
Assuming I have three classes:
- Class A: The main class - it contains an instance of both
BandC. - Class B: This class contains a method that outputs some string, call it
Greet(). - Class C: This one has a method too, but that method has to call
Greet()in the instance ofBthat is located in classA. Let's name itDoSomethingWithB()
So the program starts, in the main function I create an instance of A. A, again, creates instances of B and C. Then, A calls C.DoSomethingWithB();.
And there my problem begins: I can't access B from inside C.
Obviously, I will need to pass a pointer to B to the DoSomethingWithB() function so that I can call B.Greet() from inside C
Long explanation, short question: How do I do this?
Example code incoming:
#include <iostream>
using namespace std;
class B
{
public:
void Greet( )
{
cout<<"Hello Pointer!"<<endl;
}
};
class C
{
public:
void DoSomethingWithB( )
{
// ... b.Greet( ); Won't work obviously
}
};
class A
{
public:
B b; // Not caring about visibility or bad class/variable names here
C c;
void StartTest( )
{
c.DoSomethingWithB( );
}
};
int main( )
{
A mainInstance;
mainInstance.StartTest();
}