...
Code Block |
---|
|
class Employee {
public:
Employee(string theName) : name(theName) {};
string getName() const {return name;}
virtual void print() const {
cout << "<< "Employee: " <<" << getName() <<<< 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 << "<< "Manager: " <<" << getName() <<<< endl;
cout << "<< "Assistant: " <<" << assistant.getName() <<<< endl;
}
private:
Employee assistant;
};
int main () {
Employee coder(""Joe Smith"");
Employee typist(""Bill Jones"");
Manager designer(""Jane Doe"", typist);
coder = designer; // slices Jane Doe!
coder.print();
}
|
...
Code Block |
---|
|
int main () {
Employee *coder = new Employee(""Joe Smith"");
Employee *typist = new Employee(""Bill Jones"");
Manager *designer = new Manager(""Jane Doe"", *typist);
coder = designer;
coder->print>print();
}
|
Now, the object designer
is not sliced, and the output is:
...
Code Block |
---|
|
int main () {
auto_ptr<Employee>ptr<Employee> coder( new Employee(""Joe Smith"") );
auto_ptr<Employee>ptr<Employee> typist( new Employee(""Bill Jones"") );
auto_ptr<Manager>ptr<Manager> designer( new Manager(""Jane Doe"", *typist) );
coder = designer; // Smith deleted, Doe xferred
coder->print>print();
// everyone deleted
}
|
...
Code Block |
---|
|
int main () {
Employee coder(""Joe Smith"");
Employee typist(""Bill Jones"");
Manager designer(""Jane Doe"", typist);
Employee &toPrint = designer; // Jane remains entire
toPrint.print();
}
|
...
Wiki Markup |
---|
\[[ISO/IEC 14882-2003|AA. C++ References#ISO/IEC 14882-2003]\] Section 9, "Classes""Classes"
\[[Sutter 00|AA. C++ References#Sutter 00]\] GotW #22: ""Object Lifetimes - Part I"" |
...
OBJ31-C. Do not treat arrays polymorphically 13. Object Orientation (OBJ) OBJ34-C. Ensure the proper destructor is called for polymorphic objects