Reputation: 37
I have a bit of a problem with operator overloading and inheritance in C++.
Quick sketch:
class A {
public:
A operator+ (const A &b) const { ... }
};
class B : public A {
...
};
Now suppose I have two instances of B
, x
and y
. If I add them I will get a thing of type A
, however I want it to be of type B
.
What is the best way of accomplishing this (aside from reimplementing them in class B
) ? CRTP?
Upvotes: 0
Views: 124
Reputation: 1111
You can implement operator+
outside of the class as a template:
template<class type> type operator+(const type& left, const type& right)
{
type toReturn;
toReturn.value = left.value + right.value;
return toReturn;
}
class A {
private:
int value;
template <class type>
friend type operator+<type>(const type& left, const type& right);
};
class B : public A {
};
int main()
{
B test1, test2;
B test3 = test1 + test2;
}
This approach has certain down-sides. The compiler will aggressively try to instantiate the operator+
template for types which you don't want to define operator+
, so be aware of that.
Upvotes: 1