Home Ask Login Register

Developers Planet

Your answer is one click away!

NaturalCaliforniaRaisins February 2016

Defining an int array in a class C++

Is there any way to dynamically (I think that's the right term) define an int array in a class, the size of which is a private member variable in that same class? For example:

class Scene()
    //public member functions


        int max;
        int xcoords[max];

I've searched through other answered questions on here, but I haven't learned how to use vectors in class yet, which is what most responses suggest. Ideally, in my constructor for the class, I'd be passed an int max, with which I then initialize the xcoord array to have a size of max with entries all -1.


David van rijn February 2016

If you want dynamic sizing for your member data, you almost certainly have to store it in the heap. Which means, something like this

class Foo{
  int* data;
  Foo(int size){
    data = new int[size];
    // remember to clean up
    delete[] data;

This way, your constructor will allocate size for size ints in the heap memory when the class is created, and free it up when it is deleted.

The more official c++ way of writing the constructor is:

  Foo(int size):
    data(new int[size])

But in the end it will do the same thing.

Johannes February 2016

Consider leaving memory management to standard libraries. Instead of Arrays, use vectors.

#include <vector>
#include <iostream>

using std::vector;
using std::cout;
using std::endl;

class Scene
    vector<int> verticeData;

int LEGACY_FUNCTION(const int * data, int count)
    for (int i = 0; i < count; ++i)
        cout << " ";
        cout << data[i];
        cout << " ";

    cout << endl;
    return 0;

int main()
    Scene myscene;

    LEGACY_FUNCTION(myscene.verticeData.data(), myscene.verticeData.size());


    LEGACY_FUNCTION(myscene.verticeData.data(), myscene.verticeData.size());

    return 0;

Post Status

Asked in February 2016
Viewed 3,278 times
Voted 13
Answered 2 times


Leave an answer

Quote of the day: live life