Accessing object in an object?

Hi guys,
so I'm new in OO C++ programming. Lets say I have two objects - object A and object B defined at global scope in main.cpp file. If I want to Access function from object A in object B, what should I do?

Should I in main.cpp when defining objects use "extern" like in example below? Or should I do something else?


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
main.cpp:
extern A();
extern B();


A.h & A.cpp file:
class A {
	// ...
}

void A::function()
{
	B.f();
}


// B.h & B.cpp file:
class B {
	// ...
}

void B::f() {
	// ...
}



EDIT:

Did little test and now get this error

error: request for member 'f' in 'A', which is of non-class type 'Aclass()'

1
2
3
void Bclass::fu() {
	A.f(); // THIS LINE
}
Last edited on
Hi,

It would be clearer if you post complete compile-able code.

Some of your terminology is off a bit: A class is not an object, rather an object is an instance of a class.

There shouldn't normally be a need for extern, just include the header file of the class for which you want to use. But watch out for circular includes: A includes B and B includes A. In that case use a forward declaration of a class :

https://stackoverflow.com/questions/9119236/c-class-forward-declaration#13268263
Yes, please post your complete code.

The error you post and the code snippet you give us don't really go with the initial code you posted. Also, you don't show us what members classes A and B have.

Please give us as much information as possible. We don't want to offer possible solutions based on guesses as to what the code really contains.
Topic archived. No new replies allowed.