Constructor called at wrong time

Viewed 204

This is less of a plea for help over a problem, and more of a question about something peculiar discovered after solving a problem. I was working on my beginner OpenGL game and was attempting to write an OOP friendly rendering file. All vbo data was being stored in a model class, where it was uploaded and buffered in the constructor.

Vastly simplified structure of this from main would look something like:

int main(){
    vector <Model> Models;

    Graphics.GLInit();

    Models.push_back(Model(vertices,texcoords,36,0));

    Graphics.EnableAttributePointers();

    main loop
    {
        Graphics.draw(Models,Textures,Entities);
    }
    return 0;
}

Constructor looked like:

Model::Model(vector <vec3> &vertices,vector <vec2> &texcoords,int NumVertices,int StartVertex)
{
    iNumVertices=NumVertices;
    iStartVertex=StartVertex;

    Vertices=vertices;
    Texcoords=texcoords;

    glGenBuffers(1,&vboVertex);
    glGenBuffers(1,&vboTexcoord);
    glBindBuffer(GL_ARRAY_BUFFER,vboVertex);
    glBufferData(GL_ARRAY_BUFFER,Vertices.size()*12,Vertices.data(),GL_STATIC_DRAW);
    glBindBuffer(GL_ARRAY_BUFFER,vboTexcoord);
    glBufferData(GL_ARRAY_BUFFER,TexCoord.size()*8,TexCoord.data(),GL_STATIC_DRAW);
}

Upon calling glDrawArrays in the drawing function a segmentation fault would occur:

0xC0000005 cannot access 0x00000000 yadda yadda.

So I checked over everything countless times, making sure it all made sense. Eventually I tore apart the program, making a simpler version in which the same exact code is being used without a model class. That worked fine. Figuring something was wrong with the Model class, I eventually placed the buffering code into a separate function to be called directly after the constructor. This fixed it.

Anyways, all this begs the question of why the constructor was seemingly being called upon out of sequence; before the GLInit code. That, or there is some behavioral quirk of constructors which I am unaware of, wherein the OpenGL state machine cannot be properly modified by them for some bizarre reason. My knowledge of C++ is only spare time highschooler level, so am I missing something obvious here?

1 Answers
Related