Reputation: 769
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_;
};
Not including renderer_
in the initialization list of GraphicsManager
's constructor at all, thus implicitly calling renderer_
's default constructor. In the body of GraphicsManager
's constructor I would be assigning a properly initialized Renderer
class instance to the empty renderer_
. Is this possible to do in the body of the constructor of GraphicsManager
?
GraphicsManager(
const std::string &windowTitle,
const int &windowWidth,
const int &windowHeight
) : window_(windowTitle,windowWidth,windowHeight)
{
//doable? is window_ initialized yet at this point?
renderer_ = Renderer(window_.getHandle());
}
Adding a separate initialize(parameters)
method to the affected classes, and
using them to initialize everything instead of relying on the constructor, but thus also delegating the responsiblity of initializing to the client of the classes?
Changing the composition / hierarchy of the classes to something else?
Upvotes: 0
Views: 60
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