In C++ we know that for a pointer of class we use (->
) arrow operator to access the members of that class like here:
#include
usi
Perhaps its insightful to consider that, given
myclass obj;
auto p = &obj; // avoid `new` with plain pointers. That combination is
// safer replaced by unique_ptr or std::vector.
the following will all work and are equivalent:
p->setdata(5, 6);
(*p).setdata(5, 6);
p[0].setdata(5, 6);
0[p].setdata(5, 6);
Showing that []
is really a pointer-dereferencing operator, just with the extra functionality that you can add offsets into a plain C-array.
It's generally questionable to use C-arrays in C++ code; the obvious alternative to your example is std::vector
:
std::vector array(10);
Here, array[n]
can be used much like previously p[n]
, but
array.at(n)
)for(auto& obj: array){...}
.