Consider the implementation of the List class in your textbook. In the Iterator
ID: 3902381 • Letter: C
Question
Consider the implementation of the List class in your textbook. In the Iterator class, the function Iterator::get simply returns the value of the node to which the iterator points. Given below is the code snippet for an Iterator class and the function get. What is the error in the implementation and how can it be fixed?
class Iterator
{
public:
Iterator();
string get() const;
void next();
void previous();
bool equals(Iterator b) const;
private:
Node* position;
List* container;
friend class List;
};
string Iterator::get() const
{
return next->data;
}
a) The code for the Iterator class is erroneous because the constructor for the Iterator class should be private.
b) The code for the Iterator class is erroneous because the declaration friend class List should be in the public section.
c) The get function should return container->data.
d) The get function should return next()->data.
Explanation / Answer
Hello, the answer for this question depends on the implementation of List class. As you have not provided it, I suppose it contains a data field and listed this Iterator class as its friend class (In case if the data field is private/protected). In that case, ‘option c) The get function should return container->data’ is the right answer. Let’s go through all options. Also, please check the commented text in bold.
class Iterator
{
public:
Iterator();
string get() const;
void next(); //the return type is void, so it cannot be ‘next()->data ‘ [option D]
void previous();
bool equals(Iterator b) const;
private:
Node* position;
List* container;
friend class List;
};
string Iterator::get() const
{
return next->data; //There is no variable named next, which is the cause of error
}
a) The code for the Iterator class is erroneous because the constructor for the Iterator class should be private.
There is absolutely no need for the constructor to be private, as it doesn’t make any difference in this code
b) The code for the Iterator class is erroneous because the declaration friend class List should be in the public section.
friend classes can be declared in private section, there is no issue in that
c) The get function should return container->data.
This is the most possible answer for this question as it extract the content of current node and returns it. Assuming there is a data field in your List class implementation and Iterator class has been declared as a friend class (in case the data field is private/protected)
d) The get function should return next()->data.
The next() method returns nothing. So this statement is totally invalid.
I hope you are clear now. Thanks.