Note that there are some explanatory texts on larger screens.

plurals
  1. POWhat is the proper way to overload operators in abstract base classes?
    primarykey
    data
    text
    <p>Suppose I have an abstract base class, that just defines a container on which addition can be performed:</p> <pre><code>class Base { public: virtual ~Base() {} virtual Base operator+(const Base&amp; rhs) =0; }; </code></pre> <p>Then I want subclasses of Base to provide the actual operation:</p> <pre><code>class Derived: public Base { public: Base operator+(const Base&amp; rhs) { // won't compile // actual implementation } }; </code></pre> <p>Here is my problem: operator+() is supposed to return a new Base object, but Base being abstract it won't compile. </p> <p>I tried to get around that by using a factory to return a reference to a Base object, but then in the body of the operator I find myself doing casts, because the addition only makes sense on Derived objects. </p> <p>In any case, it feels like I am biting my own tail, is there a proper solution to this?</p> <p>UPDATE: Based on the answers so far, it seems I am using the wrong pattern. I want to separate the interface from the implementation, so that library code only has to know the interface and client code provides the implementation. I tried to do that by providing the interface as an abstract base class, and the implementation as subclasses. </p> <p>UPDATE2: My question was actually 2 questions, a concrete one (about overloading operators in abstract classes) and another about my intent (how do I allow the client to customize the implementation). The former has been answered: don't. For the latter, it seems that the Interface Class pattern I use is actually a good one to solve that problem (according to <a href="http://www.octopull.demon.co.uk/c++/implementation_hiding.html" rel="noreferrer">Griffiths and Radford</a>), it's just that I should not mess with overloaded operators.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload