Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Edited by NavBot (jp)

...

Code Block
bgColor#FFCCCC
class Employee {
public:
  Employee(string theName) : name(theName) {};
  string getName() const {return name;}
  virtual void print() const {
    cout << "&lt;&lt; &quot;Employee: " <<&quot; &lt;&lt; getName() <<&lt;&lt; endl;
  }
private:
  string name;
};

class Manager : public Employee {
public:
  Manager(string theName, Employee theEmployee) :
    Employee(theName), assistant(theEmployee) {};
  Employee getAssistant() const {return assistant;}
  virtual void print() const {
    cout << "&lt;&lt; &quot;Manager: " <<&quot; &lt;&lt; getName() <<&lt;&lt; endl;
    cout << "&lt;&lt; &quot;Assistant: " <<&quot; &lt;&lt; assistant.getName() <<&lt;&lt; endl;
  }
private:
  Employee assistant;
};

int main () {
  Employee coder("&quot;Joe Smith"&quot;);
  Employee typist("&quot;Bill Jones"&quot;);
  Manager designer("&quot;Jane Doe"&quot;, typist);

  coder = designer;  // slices Jane Doe!
  coder.print();
}

...

Code Block
bgColor#ccccff
int main () {
  Employee *coder = new Employee("&quot;Joe Smith"&quot;);
  Employee *typist = new Employee("&quot;Bill Jones"&quot;);
  Manager *designer = new Manager("&quot;Jane Doe"&quot;, *typist);

  coder = designer;
  coder->print&gt;print();
}

Now, the object designer is not sliced, and the output is:

...

Code Block
bgColor#ccccff
int main () {
  auto_ptr<Employee>ptr&lt;Employee&gt; coder( new Employee("&quot;Joe Smith"&quot;) );
  auto_ptr<Employee>ptr&lt;Employee&gt; typist( new Employee("&quot;Bill Jones"&quot;) );
  auto_ptr<Manager>ptr&lt;Manager&gt; designer( new Manager("&quot;Jane Doe"&quot;, *typist) );

  coder = designer; // Smith deleted, Doe xferred
  coder->print&gt;print();
  // everyone deleted
}

...

Code Block
bgColor#ccccff
int main () {
  Employee coder("&quot;Joe Smith"&quot;);
  Employee typist("&quot;Bill Jones"&quot;);
  Manager designer("&quot;Jane Doe"&quot;, typist);

  Employee &amp;toPrint = designer;  // Jane remains entire
  toPrint.print();
}

...

Wiki Markup
\[[ISO/IEC 14882-2003|AA. C++ References#ISO/IEC 14882-2003]\] Section 9, "Classes"&quot;Classes&quot;
\[[Sutter 00|AA. C++ References#Sutter 00]\] GotW #22: "&quot;Object Lifetimes - Part I"&quot;

...

OBJ31-C. Do not treat arrays polymorphically      13. Object Orientation (OBJ)      OBJ34-C. Ensure the proper destructor is called for polymorphic objects