Rstevoa
Rstevoa

Reputation: 271

Array declaration, size definition, and destruction in c++

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?

Upvotes: 2

Views: 186

Answers (2)

TheSOFan
TheSOFan

Reputation: 67

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

Upvotes: 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)
{}

Upvotes: 2

Related Questions