For starters, let's consider the following abstract from a project I'm currently working on. Here's the header:
class GUI {
public:
GUI& Initialize();
void DrawGUI(float width, float height);
private:
Model quad;
Shader sh;
Camera cam;
};
While this is the cpp file:
GUI& GUI::Initialize() {
quad.Initialize().LoadModel("Resources/quad.obj");
sh = Shader().Initiliaze();
sh.models.push_back(&quad);
return *this;
}
void GUI::DrawGUI(float width, float height) {
quad.SetScale(width, height, 0);
sh.RenderModels();
}
Before going straight to the problem an explanation is due. The Shader
object sh
stores pointers to a certain number of models in a vector vector<Model*> models
. These models can be rendered using the RenderModels
method.
During initialization, GUI
adds quad
to sh.models
via quad
's address &quad
. Then the method DrawGUI
can be used to scale quad
and to draw it on the screen.
The Problem:
When using DrawGUI
in my main function, the scaling has no effect!
This is due to a "mysterious" behavior that I was hoping someone could unravel for me. I already know the root of the problem, but I cannot grasp what's behind it.
Although the SetScale
function modifies the dimensions of quad
, this does not affect the rendering since (I have verified this while debugging) &quad
and sh.models[0]
have different values when DrawGUI
is called. In particular, quad
changes its address without any intervention on my part at one point between initialization and draw call. A small change fixes the problem and the scaling takes place:
void GUI::DrawGUI(float width, float height) {
sh.models[0].SetScale(width, height, 0);
sh.RenderModels();
}
But this does not help me to understand why the problem occurs in the first places. Things are made even less clear by the fact that, while the problem occurs when GUI
is declared using automatic storage, i.e. GUI gui;
, it does not appear when I allocate GUI
on the heap. In fact quad
does not change address keeping it the same as sh.models[0]
and everything works fine.
Why the different behavior between the two styles of allocation? Is there something about automatic allocation that I'm missing? Why does quad
change its address?