Let’s say i have an array of objects and i want to set variables within those objects based on their array index (0, 1, 4… etc.). Is there a way to get the object’s index (within its parent array) though a member function, that is, without passing an integer?
Made up example:
class Car
{
public:
void init();
private:
short weight;
};
void Car::init()
{
// affect 'weight' based on object's array index
}
Car myCars[7];
myCars[2].init();
Is there a way to retrieve myCars’ index (i.e. 2) from within init() without the function having received an integer from the outside?
I know this is not necessary, but i was curious whether it was possible.
Thank you.
No, the C++ language doesn’t provide such a capability. If you really need that (double check your design) you’ll have to pass it in and maintain it if the index ever changes for your object (for example if you insert in the middle of a container).