Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ class inheritance and operator overloading; do operator overloads get inherited?

Just a quick question, if I have a template class:

template <typename T>
class foo {
public:
    bool operator!=(foo& other) const {
        //...
    }

}

And then I inherit said class:

template <typename T>
class bar : public foo<T> {
    //...
}

Does the operator overload get inherited? And if not, how would I go about implementing it so that it does... because currently in my test class, this brings up an error:

for (bar<int> i(baz); i != bar<int>(); i++) {}

The ++ operator is implemented in the bar class, so that works, but the != operator is apparently not inherited. The error message is:

error: no match for 'operator!=' in 'i != bar<int>(0u, 0u)'
note: candidate is: bool foo<T>::operator!=(foo<T>&) const [with T = int]

That pretty much sums up the problem I'm having, so I'm just wondering how I'd go about inheriting the operator overload.

like image 946
Fault Avatar asked Dec 18 '25 10:12

Fault


1 Answers

Your operator definition isn't quite correct:

bool operator!=(foo& other) const {
    //...
}

should be

bool operator!=(const foo& other) const {
    //...
}

since you are trying to compare with a temporary, which can only be bound to a const reference.

like image 178
Adam Bowen Avatar answered Dec 20 '25 01:12

Adam Bowen



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!