Search code examples
c++classscopefriendaccess-control

Call a function in class members (C++)


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?


Solution

  • 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.