Pieter
Pieter

Reputation: 32765

Parameter issue with operator overload for !=

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;
}

Upvotes: 1

Views: 130

Answers (2)

Cheers and hth. - Alf
Cheers and hth. - Alf

Reputation: 145279

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

Upvotes: 1

ravi
ravi

Reputation: 11

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

Upvotes: 0

Related Questions