Note that there are some explanatory texts on larger screens.

plurals
  1. POderived class's virtual assignment operator not being called
    primarykey
    data
    text
    <p>I'm pretty new to C++, and am trying to come to grips with virtual assignment. The program below consists of an abstract base class with two data members, and a derived class with one. When I set an abstract pointer to a derived object, the program uses the abstract version of operator= rather than the derived version, even though they're both declared "virtual." What am I doing wrong here?</p> <p>Thanks in advance,</p> <p>Jay</p> <pre><code>#include &lt;iostream&gt; #include &lt;cstring&gt; class Abstract { protected: char * label; int rating; public: Abstract(const char * l = "null", int r = 0); virtual Abstract &amp; operator=(const Abstract &amp; rs); virtual ~Abstract() { delete [] label; } virtual void view() const = 0; }; class Derived : public Abstract { private: char * style; public: Derived(const char * s = "none", const char * l = "null", int r = 0); ~Derived() { delete [] style; } virtual Derived &amp; operator=(const Derived &amp; rs); virtual void view() const; }; Abstract::Abstract(const char * l , int r ) { label = new char[std::strlen(l) + 1]; std::strcpy(label, l); rating = r; } Abstract &amp; Abstract::operator=(const Abstract &amp; rs) { if (this == &amp;rs) return *this; delete [] label; label = new char[std::strlen(rs.label) + 1]; std::strcpy(label, rs.label); rating = rs.rating; return *this; } Derived::Derived(const char * s, const char * l, int r) : Abstract(l, r) { style = new char[std::strlen(s) + 1]; std::strcpy(style, s); } Derived &amp; Derived::operator=(const Derived &amp; hs) { if (this == &amp;hs) return *this; Abstract::operator=(hs); style = new char[std::strlen(hs.style) + 1]; std::strcpy(style, hs.style); return *this; } void Derived::view() const { std::cout &lt;&lt; "label: " &lt;&lt; label &lt;&lt; "\nrating: " &lt;&lt; rating &lt;&lt; "\nstyle: " &lt;&lt; style; } int main () { using namespace std; char label[20], style[20]; int rating; cout &lt;&lt; "label? "; cin &gt;&gt; label; cout &lt;&lt; "rating? "; cin &gt;&gt; rating; cout &lt;&lt;"style? "; cin &gt;&gt; style; Derived a; Abstract * ptr = &amp;a; Derived b(style, label, rating); *ptr = b; ptr-&gt;view(); return 0; } </code></pre>
    singulars
    1. This table or related slice is empty.
    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