Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing the [] operator from a pointer

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)[].

like image 875
Malabarba Avatar asked Dec 13 '11 17:12

Malabarba


People also ask

How do I access the members of a pointer?

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.

Can we use operator on pointers?

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.

Which operator is used to access a class member with respect to pointer?

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.


2 Answers

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.

like image 76
Robᵩ Avatar answered Oct 02 '22 19:10

Robᵩ


return VecPtr->operator[](0); 

...will do the trick. But really, the (*VecPtr)[0] form looks nicer, doesn't it?

like image 22
Sean Avatar answered Oct 02 '22 21:10

Sean