If you make a vector of a class of no designated size, as you reserve spaces inside the vector will it just make a default instance from the constructor?

Recommended Answers

All 6 Replies

Probably, you can check it out pretty easy.

Be careful of the word size. size is frequently used to indicate the actual number of elements currently in the vector as opposed to the number of elements for which space is allocated for vector use, which might be called capacity or size.

Fortunately you CAN'T invent a "class of no designated size" in C++. For every class its objects have fixed and defined size (remember operator sizeof).
If you mean a class with dynamically allocated members then it's a problem of this class constructor, not a vector container. That's why class constructors were invented.

i meant i created a vector of unspecified size. but when I reserve a spot then try to alter the instance an error pops up and I get a window telling me that the program has to close because it has run into an error. I just don't know what is going on.

Your question is difficult to understand, but if you mean will it construct what you have in a default constructor to each instance of said class, then yes it should.

If you are using std::vector class then probable causes are:
1. You reserve vector size then try to access its elements, but reserve member function does not construct vector elements. You need resize (not reserve) vector if you want to access new elements immediatly.
2. Your class has bad default constructor (constructor without arguments). For example:

class Bad {
    Bad() {} // Forgot to initialize pDynArr with 0.
    Bad(const char* p, int n) {
         pDynArr = new char[n];
    }
    ~Bad() { delete [] pDynArr;
private:
    char* pDynArr;
};
...
std::vector<Bad> troubles;
...
troubles.resize(10);
...

New Bad objects created after vector<Bad>::resize(k) are true bad. There are garbage values of pDynArr member in all 10 vector elements. The destructor of troubles calls Bad destructor for every 10 elements, the last one call delete [] pDynArr for undefined pointer.

Follow MosaicFuneral's advice ;)...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.