petriichuk petriichuk - 3 years ago 89
C++ Question

How to use arguments from constructor to call a constructor of another class in C++?

I have a question. I want to call a constructor of "gameWindow" from the class "Game". The problem is that if I call it from the constructor it is initialising as a local variable (example A), if I define it in as a private member - I can not use arguments of a constructor. How can I make gamewindowObj as a member from a constructor?

//example А

class Game{
public:
Game(int inWidth, int inHeight, char const * Intitle);
};

Game::Game(int inWidth, int inHeight, char const * Intitle){
gameWindow gamewindowObj=gameWindow(inWidth, inHeight, Intitle);
}


//example В

class Game{
public:
Game(int inWidth, int inHeight, char const * Intitle);
private:
gameWindow gamewindowObj=gameWindow(inWidth, inHeight, Intitle);
};
Game::Game(int inWidth, int inHeight, char const * Intitle){}

Answer Source

If you want gamewindowObj to be a data member and be initialized by the constructor's arguments, you can use member initializer list, e.g.

class Game{
public:
    Game(int inWidth, int inHeight, char const * Intitle);
private:
    gameWindow gamewindowObj;
};

Game::Game(int inWidth, int inHeight, char const * Intitle) : gamewindowObj(inWidth, inHeight, Intitle) {
//                                                          ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download