Taras
Taras

Reputation: 507

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){}

Upvotes: 1

Views: 81

Answers (1)

songyuanyao
songyuanyao

Reputation: 173014

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) {
//  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
}

Upvotes: 7

Related Questions