"su**************@yahoo.com, India" <su**************@yahoo.com>
wrote:
In his book, Stroustrup has mentioned that slicing can be a source of
surprises and errors. I am unable to understand it. Kindly give an
example where slicing can lead to surprise and error.
struct foo {
virtual int fnc() { return 5; }
};
struct bar : foo {
virtual int fnc() { return 7; }
};
void test( foo y ) {
cout << y.fnc() << '\n';
}
int main() {
bar x;
test( x );
}
What should be output on the screen? One would expect that since we
passed in a 'bar' object to test, it should output '7', but because of
slicing, it outputs '5'.
If 'test()' took a foo& or foo*, or if 'test()' were a template, then
the output would have been '7'.