What does slicing mean in C++?

前端 未结 4 1475
暖寄归人
暖寄归人 2020-12-03 18:38

It is mentioned in C++ FAQ site -- \"larger derived class objects get sliced when passed by value as a base class object\", what does slicing mean? Any sample to demonstrate

4条回答
  •  甜味超标
    2020-12-03 18:55

    Slicing means that the derived class information is lost. The base class parameter forces an object of the base class to created which share the same base-class state as the derived class. E.g:

    struct B { int x; };
    
    struct D : B { double y; };
    
    void f(B b) {}
    
    int main() {
      D d;
      f(d);
    }
    

    In the function f you will not be able to access D::y.

    Edit: Thanks to everyone for editing. Please make sure that the edit adds value. Note that

    • For structs the default inheritance is public.
    • If you fix the code, make sure you update the body too

提交回复
热议问题