If I define a pointer to an object that defines the []
operator, is there a direct way to access this operator from a pointer?
For example, in the following code I can directly access Vec
's member functions (such as empty()
) by using the pointer's ->
operator, but if I want to access the []
operator I need to first get a reference to the object and then call the operator.
#include <vector> int main(int argc, char *argv[]) { std::vector<int> Vec(1,1); std::vector<int>* VecPtr = &Vec; if(!VecPtr->empty()) // this is fine return (*VecPtr)[0]; // is there some sort of ->[] operator I could use? return 0; }
I might very well be wrong, but it looks like doing (*VecPtr).empty()
is less efficient than doing VecPtr->empty()
. Which is why I was looking for an alternative to (*VecPtr)[]
.
To access a member function by pointer, we have to declare a pointer to the object and initialize it (by creating the memory at runtime, yes! We can use new keyboard for this). The second step, use arrow operator -> to access the member function using the pointer to the object.
C++ provides two pointer operators, which are (a) Address of Operator & and (b) Indirection Operator *. A pointer is a variable that contains the address of another variable or you can say that a variable that contains the address of another variable is said to "point to" the other variable.
The class member access operator (->) can be overloaded but it is bit trickier. It is defined to give a class type a "pointer-like" behavior. The operator -> must be a member function. If used, its return type must be a pointer or an object of a class to which you can apply.
You could do any of the following:
#include <vector> int main () { std::vector<int> v(1,1); std::vector<int>* p = &v; p->operator[](0); (*p)[0]; p[0][0]; }
By the way, in the particular case of std::vector
, you might also choose: p->at(0)
, even though it has a slightly different meaning.
return VecPtr->operator[](0);
...will do the trick. But really, the (*VecPtr)[0]
form looks nicer, doesn't it?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With