0

I'm trying to create a level of abstraction for the VertexBuffer and the Vertex array with OpenGL

I have a piece of working code:

main.cpp

    glBindVertexArray(vertexArrayID);
    GLuint verticesID;
    glGenBuffers(1, &verticesID);
    glBindBuffer(GL_ARRAY_BUFFER, verticesID);
    glBufferData(GL_ARRAY_BUFFER, points*sizeof(GLfloat), &vertex[0], GL_STATIC_DRAW);
    glEnableVertexAttribArray(0);
    glVertexAttribPointer((GLuint)0, 3, GL_FLOAT, GL_FALSE, 0, 0);
    vertex.clear();

This works, fine, perfect.

But when I try to abstract it into a class for better readability like so:

VertexBuffer.h

class VertexBuffer {

    private:
        unsigned int m_RendererID;
    
    public:
        VertexBuffer(const void* data, unsigned int size);
        ~VertexBuffer();
    
        void Bind() const;
        void Unbind() const;
 };

VertexBuffer.cpp

#include "VertexBuffer.h"

VertexBuffer::VertexBuffer(const void *data, unsigned int size)  {
    glGenBuffers(1, &m_RendererID); // Here is where the problem lies
    GLCall(glBindBuffer(GL_ARRAY_BUFFER,m_RendererID))
    GLCall(glBufferData(GL_ARRAY_BUFFER,size,data,GL_STATIC_DRAW))
}

The code just doesn't works and I have narrow it down to the glGenBuffers line because if I do this:

VertexBuffer::VertexBuffer(const void *data, unsigned int size)  {
    unsigned int anotherID;
    glGenBuffers(1, &anotherID);
    GLCall(glBindBuffer(GL_ARRAY_BUFFER,anotherID))
    GLCall(glBufferData(GL_ARRAY_BUFFER,size,data,GL_STATIC_DRAW))
}

or any sort of combinations, it just works. Of course, it won't work properly if I leave it like that because I need to be able to save the VertexBufferID but I don't know why this behavior.

Any help will be immensely appreciated!

Gabe
  • 50
  • 6
  • What does `~VertexBuffer()` do? – Rabbid76 May 02 '21 at 10:52
  • Declaration for VertexBuffer destructor. – Gabe May 02 '21 at 10:53
  • No. What are you doing in the destructor? `glDeleteBuffers`? – Rabbid76 May 02 '21 at 10:54
  • Deleting the buffer ->`glDeleteBuffers(1, &m_RendererID)` – Gabe May 02 '21 at 10:54
  • 1
    Please read [OpenGL object in C++ RAII class no longer works](https://stackoverflow.com/questions/46839586/opengl-object-in-c-raii-class-no-longer-works). Set a breakpoint in the destructor, debug your code an see what happens. – Rabbid76 May 02 '21 at 10:56
  • 1
    How are you using class `VertexBuffer`? Does it obey the [rule of 3/5/0](https://en.cppreference.com/w/cpp/language/rule_of_three) (I'm guessing not). – G.M. May 02 '21 at 10:56

0 Answers0