Kidades
Kidades

Reputation: 670

Is it OK to overload operators inside the header file (when declaring the class)?

Test.h:

class Test {
private:
    int value;

public:
    Test();
    int getValue();
    void setValue(int value);

    bool operator >(Test &l) {
        if (value > l.value) {
            return true;
        }
        return false;
    }
};

Can this cause any problems? If yes, what is the right way to implement it into a cpp file? If I attempt to implement it into a cpp file, I get an error saying that the number of arguments (because the function is now not inside the class?).

Upvotes: 4

Views: 8598

Answers (2)

user4992621
user4992621

Reputation:

In theory you should be making class objects as small as possible, and be doing everything you can in small related non-member functions. The difference I suspect you're getting bitten by is that a non-static member function defined inside a class always has an 'invisible' first/last parameter (the this pointer). You may forget that, but the compiler won't...

Upvotes: 0

Galik
Galik

Reputation: 48635

I'd say for such trivial functions this is the ideal way to do it because it allows the compiler to inline them, removing the function overhead.

But you should make the functions const where possible.

So:

class Test {
private:
    int value;

public:
    Test();
    int getValue();
    void setValue(int value);

    bool operator >(const Test &l) const { // be const correct!
        if (value > l.value) {
            return true;
        }
        return false;
    }
};

The function does not modify the data members at all so I have marked it const. Also the parameter is not changed so that too I have marked const.

If you do want to implement it into a separate cpp file then you need to qualify it with the class name:

Test.h

class Test {
private:
    int value;

public:
    Test();
    int getValue();
    void setValue(int value);

    bool operator >(const Test &l) const; // declare only
};

Test.cpp

// Qualify the name with Test::
bool Test::operator >(const Test &l) const { // be const correct!
    if (value > l.value) {
        return true;
    }
    return false;
}

Also you can be a little more succinct with these functions:

// Qualify the name with Test::
bool Test::operator >(const Test &l) const { // be const correct!
    return value > l.value;
}

Upvotes: 6

Related Questions