Reputation: 29
Assume we have a class hierarchy in C++ as follows:
class A{
//...
};
class B : public A{
//...
};
A
may represent an abstract base class and have a complicated structure of derived classes.
We define a Sum
class which represents a sum of two A
objects.
Hence we'd like to overload the +
operator to take two A
objects and return the corresponding Sum
object:
Sum operator+(const &A a1, const &A a2){
//...
}
As A
is an abstract class, we may want to implement operator+()
differently for its subclasses.
For example, if A
is RealFunction
and B
is Polynomial
, we expect the result of addition of two polynomials to be a polynomial (the dynamic type) instead of the general Sum
object (as we know how to add polynomials effectively).
What design is preferred in this situation? It seems that using RTTI to check the types would fit, but many people on stack said it should be avoided.
Upvotes: 1
Views: 61