0

Sorry if the title doesn't make sense. I don't know how to word it as I'm fairly new to C++. Basically I have this:

sf::VertexArray *vArray;

If I want to access the position inside, I would have to do this:

(*vArray)[0].position = ...;

Is there a way to use the arrow notation instead? Why can't I do this: vArray[0]->position = ...;?

Any help would be appreciated!

EDIT: sf::VertexArray is part of the SFML library: https://github.com/SFML/SFML/blob/master/src/SFML/Graphics/VertexArray.cpp

3
  • 1
    Since vArray has type sf::VertexArray *, vArray[0] is just built-in pointer arithmetic, and has type sf::VertexArray. That type has no operator->, and so you cannot do ->position on it. Even if it did have sf::Vertex *operator->(), presumably it would be implemented to return a pointer to the first vertex in the VertexArray, so would only have quite limited use. I expect that's why it's not provided. Commented Sep 11, 2016 at 23:09
  • Thank you, it makes a bit more sense now. Commented Sep 11, 2016 at 23:14
  • If you have dozens of lines that use (*vArray) inside a block, you could reseat it as reference and use that reference (be careful not to delete the vArray pointer before the end of the block) vector<int> *pvi=new vector<int>(2,100); vector<int> &vref=(*pvi); cout << vref[0] << endl; cout << vref[1] << endl; Commented Sep 11, 2016 at 23:30

1 Answer 1

3

If your original line

(*vArray)[0].position = ...;

properly illustrates the semantics of your data structure, then the ->-based analogue would be

vArray->operator [](0).position = ...;

assuming sf::VertexArray is a class type with overloaded operator []. Obviously this second form is much more convoluted and requires an explicit reference to the operator member function, which is why it is a better idea to use a much more elegant first form.

Alternatively, you can force a -> into this expression as

(&(*vArray)[0])->position = ...;

but that does not make much practical sense.

You can even combine the two

(&vArray->operator [](0))->position = ...;

to arrive at something even more obfuscated and pointless.

Anyway, why do you want to have a -> in this expression? What are you trying to achieve?

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the explanation. I was just trying to set the position. I'm fairly new to C++ so I don't know how most of the syntax works; especially for pointers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.