2

So I'm unsure as to what the correct way is to do this. I have a class named someClass, with a private variable that is an array of integers. The size doesn't get defined until the constructor is called. Here's how I do it:

In someClass.h:

class someClass {
public:
    someClass();
    someClass(int size);
    ~someClass();
private:
    int* array;
}

In someClass.cpp:

someClass::someClass() {
    array = new int[9];
}

someClass::someClass(int range) {
    array = new int[range];
}

someClass::~someClass() {
    delete[] array;
}

Did I declare/define the array correctly? Would it have been much better to use a vector?

Is the destructor correct?

Rstevoa
  • 271
  • 4
  • 17

2 Answers2

2

Yes, you're doing it correctly (partially), and yes, it would be better to use a std::vector (because of the "partially" part).

The "partially" is that now you will have to provide a copy constructor and copy assignment operator for your class (and for efficiency, you might want to have a move constructor and move assignment operator as well); if you don't, you'll get double deletion errors if you ever copy the class.

std::vector encapsulates all this, so this is why you should prefer it. Not to mention that it has nice features like iterators.

Your class would then look like this:

class someClass {
public:
    someClass();
    someClass(int size);
    //no destructor necessary!
private:
    std::vector<int> array;
}
someClass::someClass()
{} // nothing special needed

someClass::someClass(int range) : array(range)
{}
Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455
2

You should also add copy ctor and copy assignment operator. Remember the rule of three!

TheSOFan
  • 67
  • 1
  • 7