struct Z {
Z();
~Z();
void DoSomethingNasty();
}
struct X {
X();
~X();
void FunctionThatCallsNastyFunctions();
}
#include "Z.h"
#include "X.h"
struct MainClass {
MainClass();
~MainClass();
private:
Z _z;
X _x;
}
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 _z
doesn't exist within the X
class; it exists within the MainClass
class. If you want to call a method on a Z
object from X
, you either need to give X
its own Z
object 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 MainClass
has both a X
member and a Z
member, they should be able to access each other. That's not how it works. MainClass
can access both of them, but the _x
and _z
objects, within their member functions, have no idea about anything outside their own class.