beginner's question on slicing

  • Thread starter subramanian100in
  • Start date
S

subramanian100in

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.

Thanks
V.Subramanian
 
Z

Zeppe

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.

ex.

try{
throw std::runtime_error("example error");
}
catch(std::exception e){
std::cout << "there has been an error: " << e.what() << "\n";
}

Regards,

Zepp
 
D

Daniel T.

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'.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,045
Latest member
DRCM

Latest Threads

Top