2

I have a class called Room, the Room class has setPrice and display function.

I stored room objects in a vector:

room.push_back(Room("r001", 1004, 2, "small"));
room.push_back(Room("r002", 1005, 2, "small"));
room.push_back(Room("r003", 2001, 4, "small"));
room.push_back(Room("r004", 2002, 4, "small"));

In my main function, i create a display function to display all rooms. Here is my code:

void displayRoom()
{
    vector<Room>::iterator it;
    for (it = room.begin(); it != room.end(); ++it) {
         *it.display(); // just trying my luck to see if it works
    }
}

But it does not call the Room's display method.

How do I call the Room(class)'s display method (no argument) and setPrice(1 argument) method?

4 Answers 4

12

Dereferencing has higher priority than member access. You could add parens ((*it).display()), but you should just use the shortcut that was introduced long long ago (in C) for this: it->display().

Of course the same rule applies for pointers and everything else that can be dereferenced (other iterators, smart pointers, etc.).

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

3 Comments

Thanks for the answer and explanation. Chosen by workable solution and first answerer.
If there anyway to call specific vector element's function. Like: room[2]->setPrice(200)
@cpp_noob: room[2] gives you something. It it's an object, call the method as you would on any object (room[2].setPrice(200)). If that something needs to be dereferenced again, you need to dereference it - again (*(room[2])).setPrice(200) or room[2]->setPrice(200).
3

Try (*it).display() or simply it->display().

Comments

1

Iterators are a bit like pointers. So you want either:

it->display();

or:

(*it).display();

1 Comment

The second is wrong, unless it's a vector of Room * (in the example, it isn't - and if it was, the first is wrong instead).
0

Using Vector, you can also use classic form

for(size_t x = 0; x < room.size(); x++) {
    room[x].display(); //for objects
    //room[x]->display(); //for pointers
}

Comments

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.