views:

95

answers:

2

I'm trying to define an overload for the != operator. My code is as follows. (Update: outdated code. If one of two article pointers points to NULL, this code will crash.)

bool ArticleContainer::ArticleIterator::operator!=(const ArticleIterator& artit) {
    if (this->article == NULL && artit.article == NULL)
        return false;
    else if (this->article->GetID() != artit.article->GetID())
        return true;
    else if (this->article->GetName() != artit.article->GetName())
        return true;
    else
        return false;
}

When I put a breakpoint on its first line of code, I saw this in the debugger.

this - 0x22fedc

artit - Unable to create variable object

Apparently the function can't access artit, so it crashes. What am I doing wrong?

Edit: the call happens here.

for (ArticleContainer::ArticleIterator art = cont.Begin(); art != cont.End(); art++) {
    cout << art << "\n";
}

Basically, I walk through a list of articles until I encounter the sentinel.

I just tested cont.End() right before the for loop:

const ArticleIterator& End() const { return *tail; }

With tail:

Name : tail
    Details:0x571900

Edit: operator++ code is as follows:

void ArticleContainer::ArticleIterator::operator++(int i) {
    this->article = this->next->article;
    this->next = this->next->next;
}
A: 

bool ArticleContainer::ArticleIterator::operator!=(const ArticleContainer::ArticleIterator& artit);

ravi
that would have been compiler error..not at run time.
Naveen
+1  A: 

I think the intent of your code is wrong, but technically you can try this:

bool ArticleContainer::ArticleIterator::operator!=(const ArticleIterator& artit) {
    if (article == NULL && artit.article == NULL)
        return false;
    if (article == NULL || artit.article == NULL)
        return true;
    if (article->GetID() != artit.article->GetID())
        return true;
    if (article->GetName() != artit.article->GetName())
        return true;
    return false;
}

However, even considering only the technical, I'd rather express operator!= in terms of operator==.

Cheers & hth.,

Alf P. Steinbach
I was just looking back at my code and you're right, I'm doing some weird stuff. I took casablanca's comment to heart and I rewrote the function. Usually I'd write `operator==` and negate the result to create `operator!=`, but my school assignment said specifically that I should create `operator!=`. That's why I didn't create `operator==`.
Pieter
Hm. Well, small point, I didn't see that when I copied the code: the functions should be `const` (place a `const` before `{`). Also, while I'm on the general advice track :-), as a general guideline comparison functions are implemented as non-member functions, since that better supports using them with arguments of derived classes, but in this case I don't think that matters. Cheers,
Alf P. Steinbach