Tuesday, April 08, 2008

C++: Object slicing and pass by value

In C++ , when a object is passed by value to a function that accepts a parameter then object slicing might happen. Consider the following class

class Base {
public:
virtual const char * toString() throw();

};

class Derived : public Base {
public:
virtual const char* toString() throw();
};

Derived derived;
Base base;

void doSomething(Base base){
....
}

doSomething(base);
doSomething(derived);


now we have 2 classes Base and Derived with a common virtual function that have been overridden in the derived class . We create 2 objects "derived" and "base".

Both of them are passed to the function doSomething . What happens in this case .

In the first case , it works the way its supposed to . In the second case , object slicing takes place and the members that are just of derived class are chopped off and the virtual function of the base class is called.

No comments: