How to call a method of a method

I'm not even sure how to ask this.

I have a vector of objects.

I have methods to manipulate these objects.

I want to manipulate an object at vectorName.at(position)

Say my method is setFoo()

I can myObject.setFoo(bar) for an object in the wild, but how do I do that for the object vectorName.at(postion) ???

I think this is what you want to do:
1
2
3
4
5
std::vector<MyObject> myObjects;

// ... Add some elements and stuff

myObjects[position].setFoo(bar);


Putting an integral type inbetween the "[]" brackets allows you to access elements of a vector, similar to arrays. From there just treat it like a normal object. If you don't like the way it looks or think it's too long, you could also shorten the name by using either a pointer or reference to an element.

Reference:
1
2
3
4
5
6
7
8
std::vector<MyObject> myObjects;

// ... Add some elements and stuff

MyObject& myObjectReference = myObjects[position];
// If your compiler supports the C++11 auto feature, you could also:
// auto& myObjectReference = myObjects[position];
myObjectReference.setFoo(bar);


Pointer:
1
2
3
4
5
6
std::vector<MyObject> myObjects;

// ... Add some elements and stuff

MyObject* myObjectPointer = myObjects[position];
myObjectPointer->setFoo(bar);
Last edited on
Topic archived. No new replies allowed.