Z.h
struct Z {
Z();
~Z();
void DoSomethingNasty();
}
X.h
struct X {
X();
~X();
void FunctionThatCallsNastyFunctions();
}
MainClass.h
#include "Z.h"
#include "X.h"
struct MainClass {
MainClass();
~MainClass();
private:
Z _z;
X _x;
}
X.cpp
X::FunctionThatCallsNastyFunctions() {
//How can I do this? The compiler gives me error.
_z.DoSomethingNasty();
}
What should i do in order to call DoSomethingNasty() function from _z object?
The compiler is giving you an error because
_zdoesn’t exist within theXclass; it exists within theMainClassclass. If you want to call a method on aZobject fromX, you either need to giveXits ownZobject or you have to pass one to it as a parameter. Which of these is appropriate depends on what you’re trying to do.I think your confusion may be this: You think that because
MainClasshas both aXmember and aZmember, they should be able to access each other. That’s not how it works.MainClasscan access both of them, but the_xand_zobjects, within their member functions, have no idea about anything outside their own class.