Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?).

like image 543
Kidades Avatar asked Oct 30 '25 15:10

Kidades


1 Answers

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;
}
like image 110
Galik Avatar answered Nov 01 '25 06:11

Galik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!