fork download
  1. #include <iostream>
  2.  
  3.  
  4. class MyClass {
  5. public:
  6. virtual void show(const std::string& s) const {
  7. std::cout <<s<<": "<< "I'm a MyClass" << std::endl;
  8. }
  9. };
  10. class MySubClass : public MyClass{
  11. public:
  12. int r=10;
  13. void show(const std::string& s) const override {
  14. std::cout <<s<<": "<< "I'm a MySubClass with r=" << r << std::endl;
  15. }
  16. };
  17.  
  18. void test_slicing() {
  19. MySubClass xyz;
  20. xyz.show("original object");
  21. //... // lots of code
  22. //... // lots of code
  23. //... // lots of code
  24. MyClass uvw = xyz; // forgot to replace -> slicing error !
  25. uvw.show("wrong copy");
  26. auto tuv = xyz; // let type inference do the job
  27. tuv.show("right copy");
  28. }
  29.  
  30. int main(int argc, const char * argv[]) {
  31. test_slicing();
  32. }
Success #stdin #stdout 0.01s 5280KB
stdin
Standard input is empty
stdout
original object: I'm a MySubClass with r=10
wrong copy: I'm a MyClass
right copy: I'm a MySubClass with r=10