1

I'm trying to create a textureLoader class for my openGL project and I can't initialize an array of textures inside of my class constructor because the the array won't accept anything unless it's a const int.

To paint you a simple picture...

myFunction(NUM)
  {
  GLuint textures[NUM];
  }

My past Failures

myConstructor(const int& num)
  {
   GLuint textures[num] //error: expression must have a constant value
  }

myConstructor(int num)
{
std::vector <GLuint> textures(num);//works but wait
glGenTextures(num, textures) // <--- doesn't work cause vectors. 
}

myConstructor(int num)
{
const int PLEASE_WORK = num;
GLuint textures[PLEASE_WORK]; // doesn't work. 
3
  • What you tried (except the vector method) is called Variable-length arrays, which is supported in C99 but not in C++ IIRC. Commented Jun 15, 2015 at 23:35
  • I will look that up, thank you. I was thinking at least the third option should have worked. Commented Jun 15, 2015 at 23:40
  • 2
    it doesn't because the size of the array is not known during compilation. Commented Jun 15, 2015 at 23:42

1 Answer 1

3

Your second options is close, you can get at the underlying array of the vector by calling .data()

myConstructor(int num)
{
    std::vector <GLuint> textures(num);
    glGenTextures(num, textures.data());
}

Assuming glGenTextures has a signature like

void glGenTextures(int, GLuint*)

I don't know much about this function, but be careful who owns that array. The vector will fall out of scope after your constructor so I'm hoping that glGenTextures will copy whatever it needs. Otherwise if the array needs to persist

myConstructor(int num)
{
    GLuint* textures = new GLuint[num];
    glGenTextures(num, textures);
}

But then I'm not sure who is supposed to clean up that memory.

Sign up to request clarification or add additional context in comments.

7 Comments

Yes, thank you, I will keep the scope of those variables in mind. Is there any way to do it using a const int& or anything other than vectors? Or is that my only alternative.
FYI: std::vector::data is c++11
@BryantheLion See the second half of my answer (using new), that is your alternative.
@Tas It is halfway through 2015, I would hope people are using (at least) C++11 compilers, otherwise they should make a point of specifying which compiler they are targeting.
@BryantheLion Sure that is a valid option. Keep a pointer to that array as a member variable, then call delete[] your_array in your destructor.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.