Marcus
Marcus

Reputation: 77

Initializing variables in definition and constructor - which is used

I am attempting to learn C++ and programming and thus I'm implementing some of the data structures in the STL.

As for my version of vector, I have two constructors, where one of them allows you to specify a location in memory for storage, if you so please. If not I have set the address of the internal data to nullptr.

I'm wondering how this will behave. Using the first constructor, I assume m_data will be set to nullptr, but what happens in the second case? Is m_data first set to nullptr, and then overwritten in construction? Is there a reason to keep the definition as nullptr in the definition, or should I just use the initializer list in both cases?

Here is the code:

template <typename T, size_t S = 0>
class custom::vector {
private:
    T* m_data = nullptr;
    size_t m_size;
    size_t m_capacity;

    T* m_future_data = nullptr;
    size_t m_future_cap;
public:
    // Constructors
    vector() : m_size(S), m_capacity(S) {}
    vector(T* destination, const size_t& capacity) : m_size(S) {
        m_data = destination;
        m_capacity = capacity;
    }
// .... rest of class

Upvotes: 0

Views: 39

Answers (1)

MSalters
MSalters

Reputation: 179819

It's tricky so see in your specific case, because T* is a pointer, and pointers do not have constructors. If you have a member with class type, you can see which constructor is called.

What you'll then see is that members are initialized (ctor, not assignment) once. The initializer used will be the one in the initializer list, if one is available there, or from the member definition if there's no initializer in the initializer list.

As for the question whether you should keep the default for m_data, I'd say no. The main reason for that is that you should have a proper class invariant, and I suspect that invariant should link m_data and m_size. But m_size has no default in its definition - it could be S, perhaps. But you should be consistent there.

Upvotes: 1

Related Questions