Question

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?

Was it helpful?

Solution

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

OTHER TIPS

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

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

it->display();

or:

(*it).display();

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
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top