F
F
Flaker2013-12-26 22:54:15
C++ / C#
Flaker, 2013-12-26 22:54:15

How can C++ create an instance of a class that is visible from the methods of another class?

Actually, how to make an object available anywhere?
The first thing that came to mind:

CGameHud* CGameHudInstance;

int main(int argc, char** args)
{
  CGameHudInstance = new CGameHud(argc, args);
  return 0;
}

But in other files CGameHudInstance is no longer visible.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry, 2013-12-26
@Flaker

Strictly speaking, the use of global variables in C++ is rare. This is legal, but mostly for compatibility with C. C++ uses other techniques to pass context, such as "passing by pointer" (below). It's also worth mentioning that global variables come with some nuances, such as problems with the initialization sequence.
But judging by your question, you don't need global variables. It will be enough code like this:

/* 
 * gameinstancehandler.h 
 */

class GameInstanceHandler{
public:
    GameInstanceHandler(CGameHud *instance):
        mInstance(instance){}

private:
    CGameHud *mInstance;
    // something other here
}

#inlucde <gameinstancehandler>

int main(int argc, char **args){
    CGameHudInstance *gameHub = new CGameHud(argc, args);
    GameInstanceHandler *handler = new GameInstanceHandler(gameHub);

    return 0;
}

Here the context is passed by pointer. Objects whose behavior depends on other, already created objects, simply receive pointers to them in the constructor, store it "on their own" and interact with them through the stored copy of the pointer.
PS Since this is a newbie question, let me give you one more piece of advice: when declaring a pointer, write an asterisk before the identifier, not after the type.
int *a; // хорошо, a — это указатель.
int* b; // плохо, но допустимо.
int* c, d; // совсем плохо, c — указатель на int, d — просто переменная типа int.

int *e, *f; // при такой же записи все понятно сразу.

F
Fat Lorrie, 2013-12-27
@Free_ze

Judging by the example, a singleton is needed here.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question