Iterator FAQ


Q: What does it mean to overload operators in C++?

C++ provides a number of operators that have various purposes. Some such operators include +,-,[],*,++, ==, != and --. When you create an object, you can define the behavior of each of these operators when used on your object. This is known as operator overloading.
Each operator has slightly different syntax to overload. Some have arguments, and they each have varying return types. Below is an example of overloading the != operator in a class:

bool operator !=(const MyClass& myClass){  //where MyClass is the name of the class you are writing
    if(this.variable != myClass.variable){
        return true;	
    }
    return false;
}

See this website for more information about operator overloading.

Q: Why should the ++ operator return *this?

When you first think about the ++ operator, you might think it should just return void. After, all, we don't usually use it like a function, right? But the truth is, we sometimes do. Consider the following function:

int add(int x, int y){
    return x+y;	
}

I can call this function using basic int variables, like so:

int num = 5;
int num2 = 7;
add(num, num2);	

However, I can also call this function using a pre-increment operator, and it will pass the int right after it is incremented:

add(++num, ++num2);
If the pre-increment operator didn't return the object itself, it would return void, and therefore, it would pass void into the function, not an integer. By returning *this at the end of your increment operator, you return the object itself after the increment, and thus you can pass the incremented object into another function.

Q: Why should the end iterator point one past the end of the array?

This one makes more sense if you think about how we use iterators, typically in a for loop:

for(vector::iterator it = myvector.begin(); it != myvector.end(); it++){
    cout << *it << endl;	
}
Notice that we always loop until it doesn't equal the end iterator. If the end iterator were pointing at the last element of the array, that means we would loop until the last element, but not including the last element. If, instead, the end iterator points one past the end, we will always visit the last element as well.

Q: I've overloaded everything, but my IDE doesn't like me saying: "iter++"

Luckily this is a simple fix! The "++" operator that we are having you implement is actually the preincrement and not the postincrement operator. saying ++iter and iter++ actually do different things, so if you want to use iter++ in your lab you are going to have to overload a different operator. While you are welcome to try it, it is much easier for this lab to just overload the preincrement operator and use ++iter in your code instead.