SatView: Pointer Perfect, part 4 - Object Slicing
(Page 5 of 5 )
It sounds pretty fictional, but have you ever heard of "Object Slicing" in C++? Oh the fun you can have with inheritance and base class usage! Where I complained that pointer casting could show no respect for identity, pointers actually help you save identity in the following case:
class MyBaseClass {
public:
virtual ~MyBaseClass() {}
virtual void bar() const { (void)printf(“MyBaseClass::bar();\n”); }
};
class MyDerivedClass : public MyBaseClass
{
public:
virtual ~MyDerivedClass() {}
virtual void bar() const { (void)printf(“MyDerivedClass::bar();\n”); }
};
/* this will slice */
void foo(MyBaseClass param) {
param.bar();
}
void test() {
DerivedClass myObj;
foo(myObj);
}
The test() function calls foo() and passes an object by value. This object is correctly derived from MyBaseClass, but when we pass it to foo() only the copy constructor of MyBaseClass is being called upon! This doesn’t maintain the virtual table and the baseclass is not aware of any virtual derived function it should call upon instead of its own. So the output is “MyBaseClass::bar();”!
One way to prevent this from happening is by passing the object by reference, making foo() use the same instance leaving the vtable intact:
/* this will not slice */
void foo(MyBaseClass *param) {
param->bar();
}
or
/* neither will this */
void fooRef(MyBaseClass ¶m) {
param.bar();
}
Either function will output “MyDerivedClass::bar();”. You see that slicing is nothing more than casting and copying a derived object back to its base object, making it smaller than the original derived version. The usage of pointers or references prevents copies being made and thus prevents possible slicing of objects.
I hope you found these articles about pointers useful and that you will stick around through the remaining series, all the way up to the SatView application. Any questions can be mailed to jun.nakamura@gmail.com.
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |