Less Than Overload C++

Viewed 85
struct nodeStructType {
    char letter;
    int count;
};

struct node {
    nodeStructType data;
    node* left;
    node* right;

    bool operator <(const node* comp)
    {
        return data.letter < comp->data.letter;
    }

};

typedef node* nodePtr;

Hi! I'm working on a project and am overloading the < operator like this. However, when calling

a = myTree.GetANode('a', 0);
b = myTree.GetANode('b', 0);

    if (a < b)
    {
        printf("yay!");
    }

, a and b both being nodePtr's, it is not returning true. GetANode function just sets data.letter to 'a' and 'b'

1 Answers

Declare the operator like

struct node {
    nodeStructType data;
    node* left;
    node* right;

    bool operator <(const node &comp) const
    {
        return data.letter < comp.data.letter;
    }

};

And call it like

if ( *a < *b)
{
    printf("yay!");
}

Or

if ( a->operator <( *b ) )
{
    printf("yay!");
}

Otherwise in this if statement

if (a < b)
{
    printf("yay!");
}

there are compared two pointers and your operator is not called.

Related