Copying a polymorphic object by value can easily result in the object being sliced. That is, only part of the information associated with the object is copied, and the remaining information is lost.
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();
}
|
In this code, the object designer of class Manager is copied by value to the object coder of class Employee. This results in the object being sliced, and only the Employee information is copied. Hence, the print() statement results in the output:
Employee: Jane Doe
The information about Jane Doe's assistant is lost.
Assuming exactly the same class structure as above, if pointers to the objects are used so that objects are copied by reference, then slicing does not occur.
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();
}
|
Now, the object {[designer}} is not sliced, and the output is:
Manager: Jane Doe
Assistant: "Bill Jones"
Slicing results in information being lost which could lead to a program not working properly, and hence to a denial of service attack.
Rule |
Severity |
Likelihood |
Remediation Cost |
Priority |
Level |
|---|---|---|---|---|---|
OBJ32-C |
1 (low) |
2 (probable) |
1 (high) |
P2 |
L3 |