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

    private:

        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.

Answers


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;
public:
  Foo(int size){
    data = new int[size];
  }
  ~Foo(){
    // 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
{
public:
    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;
    myscene.verticeData.emplace_back(3);
    myscene.verticeData.emplace_back(4);
    myscene.verticeData.emplace_back(5);

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

    myscene.verticeData.clear();
    myscene.verticeData.emplace_back(1);
    myscene.verticeData.emplace_back(7);

    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

Search




Leave an answer