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-&gt;print>print();
}

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

...

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

  coder = designer; // Smith deleted, Doe xferred
  coder-&gt;print>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, &quot;Classes&quot;"Classes"
\[[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