What does slicing mean in C++?

前端 未结 4 1470
暖寄归人
暖寄归人 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:57

    Slicing is basically removing the derivedness of the derived class object to behave as if it were a base class object.

    For ex:

    class A
    {
    public:
       int x;
    };
    
    class B : public A
    {
    public:
       int y;
    };
    
    void test(A a)
    {
    }
    
    int main()
    {
     B b;
    test(b); // here the object b will be visible as A object in method test
    //none of the B's data or methods are available.
    }
    

提交回复
热议问题