Search code examples
c++vectordereference

Using the dereference operator in C++ vectors


Whet is the difference between 1) and 2) and what will be the values of them:

1) double h = (*Jill_data)[5];
2) double h = *Jill_data[5];

when we have a vector<double>* Jill_datawith the data: {2, 4, 6, 8, 10, 12, 14, 16}.


Solution

  • Talking of operator precedence in picture, as mentioned by FedeWar, the following C++ style pseudo-code may make it clearer:

    double h1 = Jill_data . DeferenceThePointer . Access_Index_5;
    double h2 = Jill_data . Access_Index_5 . DeferenceThePointer;
    

    In first case, Jill_data will be de-referenced (pointer-indirection), which will work, since Jill_data is a pointer. It gives a vector object. Then it accesses the index, which calls vector::operator[] which is a valid operation. You get a double value.

    In second case, you are accessing the 6th element ([5]) of Jill_data, which is valid, and it gives vector. Then you try to call operator* on vector, which is not implemented by vector class, hence you'd get "Invalid indirection" or similar error. This cannot anyway be assigned to a double