jms
jms

Reputation: 769

c++: constructor dependancy between member classes

What would be the preferred approach to initializing the following construct? The problem with the following example is that in order to initialize renderer_ using it's constructor, I need information from the class window_, but the information is only availeable after said class has been initialized, and both instances are initialized concurrently as they are both members of the same class.

class GraphicsManager
{
public:
    GraphicsManager(
        const std::string &windowTitle,
        const int &windowWidth,
        const int &windowHeight
        ) : window_(windowTitle,windowWidth,windowHeight),
            renderer_(window_.getHandle()); //IMPOSSIBLE, I presume
private:
    Window window_;
    Renderer renderer_;
};

class Window
{
public:
    Window() : windowHandle_(NULL);
    Window(const std::string &title, const int &width, const int &height);
    ~Window();
    SDL_Window *getHandle();
private:
    SDL_Window *windowHandle_;
};

class Renderer
{
public:
    Renderer() : rendererHandle_(NULL);
    Renderer(SDL_Window *WindowHandle);
    ~Renderer();
private:
    SDL_Renderer *rendererHandle_;
};

Upvotes: 0

Views: 60

Answers (1)

Kristian Duske
Kristian Duske

Reputation: 1779

and both instances are initialized concurrently as they are both members of the same class.

Member variables are initialized in the order in which their declarations appear in the class. Did you try this:

GraphicsManager(
    const std::string &windowTitle,
    const int &windowWidth,
    const int &windowHeight
    ) : window_(windowTitle,windowWidth,windowHeight), renderer_(window_.getHandle())
{
}

This should work just as well.

Upvotes: 3

Related Questions