MathuSum Mut MathuSum Mut - 4 months ago 33
C++ Question

How should class fields be declared in C++?

I need to declare and initialize a vector as a field of a class named


I am torn between these two declaration methods, the first is "on the heap", and the second "on the stack" (or at least, that is my interpretation).

  1. vector<int>* field = new vector<int>();

  2. vector<int> field = vector<int>();

If I choose to declare in style number 1, I need to call delete in the destructor of the class.

Which one should I choose, and why?

Also, if the class is initialized on the heap (ie.
PixelOperator* op = new PixelOperator();
), are fields initialized on the stack initialized on the heap?


Your intuition is wrong in this instance. Approach (2) does not necessarily put the vector on stack. If PixelOperator object is declared locally and thus put on stack, the vector is put on stack as well, but if the PixelOperator object is put on heap using new operator, the vector also gets put on heap as part of that object. The difference in this instance would be that in approach (2) the vector is part of a contiguous block of memory together with other object fields, and in approach (1), the block of memory containing the object has in it address of another block of memory, which contains the vector. Of course, in approach (1) the vector ends up on heap regardless of whether the PixelOperator object is put on heap or on stack. Approach (2) is generally more desirable, as it allows for more transparency determining where the object gets allocated.