Search code examples
c++classcall

c++ call outside class functions


Is there an way for an Inside class to call the Outside class functions directly? Instead of having to check if a boolean is true or not.

Like this:

Inside Class

class Inside {

public:
    Inside()
    {
    }
    ~Inside()
    {
    }

    Update()
    {
        if(buttonpress)
        {
         //call Outside::LoadGame();
        }
    }

}

Outside Class

class Outside {

public:
   Outside();
   ~Outside();
   void LoadGame()
   {
     //Load Game
   }

   Inside* insideObject;

   void Update()
   {
     insideObject->Update();
   }


}

Solution

  • It's not possible for you to do, not without the Inside::Update function having a reference to an Outside object.

    The easiest solution is to call Update passing this as argument:

    class Inside
    {
        ...
    
        void Update(Outside* outside)
        {
            outside->LoadGame();
        }
    };
    
    // ...
    
    void Outside::Update()
    {
        inside->Update(this);
    }
    

    Another solution is passing this as an argument to the constructor when creating the inside object in the Outside class.


    However, this couples the two classes very tightly, which can be a sign of bad design. Before you implement this, you should ask yourself "Do I really need this tight coupling? Can there be other ways of solving the problem with better design? And what is the problem I try to solve anyway?"