Accessing function from constructing class

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:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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?
Last edited on
You can provide the this pointer of class A:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
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;
}


[EDIT]
Making the code example working...
Last edited on
No - as this has a cyclic dependency. A requires B and B requires A

Last edited on
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.

The following compiles:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <iostream>
using namespace 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.
Last edited on
Topic archived. No new replies allowed.