Note that there are some explanatory texts on larger screens.

plurals
  1. POHow does the abstract base class avoid the partial assignment?
    text
    copied!<p>As is talked about in Item 33 in "More Effective C++", the assignment problem is</p> <pre><code>//Animal is a concrete class Lizard:public Animal{}; Chicken:public Animal{}; Animal* pa=new Lizard('a'); Animal* pb=new Lizard('b'); *pa=*pb;//partial assignment </code></pre> <p>However, if I define <code>Animal</code> as an abstract base class, we can also compile and run the sentence:<code>*pa=*pb</code>. Partial assignment problem is still there.<br> See my example:</p> <pre><code>#include &lt;iostream&gt; class Ab{ private: int a; double b; public: virtual ~Ab()=0; }; Ab::~Ab(){} class C:public Ab{ private: int a; double b; }; class D:public Ab{ private: int a; double b; }; int main() { Ab *pc=new C(); Ab *pd=new D(); *pc=*pd; return 0; } </code></pre> <p>Do I miss something? Then what's the real meaning of the abstract base class?</p> <p><strong>I got the answer by myself. I missed a code snippet in the book.</strong><br> Use protected <code>operator=</code> in the base class to avoid <code>*pa=*pb</code>. Use abstract base class to avoid <code>animal1=animal2</code>.Then the only allowed expressions are <code>lizard1=lizard2;chicken1=chicken2;</code><br> See the code below: </p> <pre><code>#include &lt;iostream&gt; class Ab{ private: int a; double b; public: virtual ~Ab()=0; protected: //!!!!This is the point Ab&amp; operator=(const Ab&amp;){...} }; Ab::~Ab(){} class C:public Ab{ public: C&amp; operator=(const C&amp;){...} private: int a; double b; }; class D:public Ab{ public: D&amp; operator=(const D&amp;){...} private: int a; double b; }; int main() { Ab *pc=new C(); Ab *pd=new D(); *pc=*pd; return 0; } </code></pre>
 

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