Nick Heiner
Nick Heiner

Reputation: 122580

C++: Inheritance and Operator Overloading

I have two structs:

template <typename T>
struct Odp
{
    T m_t;

    T operator=(const T rhs)
    {
        return m_t = rhs;
    }
};

struct Ftw : public Odp<int>
{
    bool operator==(const Ftw& rhs)
    {
        return m_t == rhs.m_t;
    } 
};

I would like the following to compile:

int main()
{
    Odp<int> odp;
    odp = 2;

    Ftw f;
    f = 2; // C2679: no operator could be found
}

Is there any way to make this work, or must I define the operator in Ftw as well?

Upvotes: 9

Views: 5049

Answers (1)

jpalecek
jpalecek

Reputation: 47770

The problem is that the compiler usually creates an operator= for you (unless you provide one), and this operator= hides the inherited one. You can overrule this by using-declaration:

struct Ftw : public Odp<int>
{
    using Odp<int>::operator=;
    bool operator==(const Ftw& rhs)
    {
        return m_t == rhs.m_t;
    } 
};

Upvotes: 22

Related Questions