Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>As long as <code>value</code> is defined only in the base class, and the operation doesn't need to access any derived members, you might be able to get away with only defining the base operator and letting implicit type casting handle the rest. As for errors with different types, it might be worth a small sacrifice to use an enum-based system to track the types, and then do a simple comparison to check for invalid conditions.</p> <pre><code>enum eTypeEnum {BASE, DER1, DER2}; class Base { public: virtual ~Base(){} Base(double value) : eType(BASE),value(value) {} Base(const Base&amp; B) { value=B.value; } Base operator+ (const Base&amp; B) const { if (eType != B.eType) return -1; //error condition return Base(value+B.value); } double getVal(){return value;} protected: eTypeEnum eType; double value; }; class Derived1 : public Base { public: Derived1(double value) : Base(value) {eType = DER1;} }; class Derived2 : public Base { public: Derived2(double value) : Base(value) {eType = DER2;} }; int main() { int tmp; Derived1 a(4.0); Derived2 b(3.0); Base c(2.0); cout &lt;&lt; "aa:" &lt;&lt; (a+a).getVal(); // 8 cout &lt;&lt; "\nbb:" &lt;&lt; (b+b).getVal(); // 6 cout &lt;&lt; "\nba:" &lt;&lt; (b+a).getVal(); // 7 cout &lt;&lt; "\nab:"&lt;&lt; (a+b).getVal(); // 7 cout &lt;&lt; "\ncc:"&lt;&lt; (c+c).getVal(); // 4 cout &lt;&lt; "\nac:"&lt;&lt; (a+c).getVal(); // 6 cout &lt;&lt; "\nbc:" &lt;&lt; (b+c).getVal(); // 5 cout &lt;&lt; "\nabc:" &lt;&lt; (a+b+c).getVal();// 9 cout &lt;&lt; endl; cin &gt;&gt; tmp; return 0; } </code></pre> <p>Outputs: aa:8 bb:6 ba:-1 ab:-1 cc:4 ac:-1 bc:-1 abc:1</p> <p>The only issue I see is that when chaining multiple operations together, the casting screws up the handling. Here, <code>a+b+c</code> 432 evaluates as <code>(a+b)+c</code> so the <code>a+b</code> bit experiences the error condition (returning -1), but gets cast as a <code>Base</code> which lets <code>(-1)+c</code> return '1'.</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.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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