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?
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).
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.
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).
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.
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;
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With