Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 599
Nick Heiner Avatar asked Aug 04 '10 23:08

Nick Heiner


People also ask

What is inheritance and operator overloading?

All overloaded operators except assignment (operator=) are inherited by derived classes. The first argument for member-function overloaded operators is always of the class type of the object for which the operator is invoked (the class in which the operator is declared, or a class derived from that class).

What is C inheritance?

Inheritance is one of the key features of Object-oriented programming in C++. It allows us to create a new class (derived class) from an existing class (base class). The derived class inherits the features from the base class and can have additional features of its own.

Does C support operator overloading?

This feature is present in most of the Object Oriented Languages such as C++ and Java. But C doesn't support this feature not because of OOP, but rather because the compiler doesn't support it (except you can use _Generic).

Can function overloading be used in inheritance?

Inheritance: Overriding of functions occurs when one class is inherited from another class. Overloading can occur without inheritance. Function Signature: Overloaded functions must differ in function signature ie either number of parameters or type of parameters should differ.


1 Answers

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;
    } 
};
like image 102
jpalecek Avatar answered Sep 21 '22 15:09

jpalecek