What is object slicing?

Asked 2 years ago, Updated 2 years ago, 96 views

I heard it somewhere, but it doesn't come out What is object sliding?

c++ inheritance object-slicing

2022-09-21 18:01

1 Answers

Slicing is assigning child class objects to objects in the parent class.

For example: Base* baseptr = new Child()

Let's take a closer look.

using namespace std;

class Base {
public:
    void printBase(){
        cout << "print Base" << endl;
    }
};

class Child : public Base {
public:
    void printChild(){
        cout << "print Base" << endl;
    }

};

int main()
{
    Child *childPtr = new Child();
    Base *basePtr = childPtr;

    cout << "childPtr : " << childPtr << ", basePtr : " << basePtr << endl;
    childPtr->printBase(); // possible
    childPtr->printChild(); // possible

    basePtr->printBase(); // possible
    //basePtr->printChild(); //Not possible

}
childPtr : 0x100100e20, basePtr : 0x100100e20
print Base
print Child
print Base
Program ended with exit code: 0

basePtr is clearly pointing to an object such as childPtr basePtr loses information about Child.

In this way, since the attributes of the child class cannot be used completely, it is expressed as slitting in the sense that they have been cut off.


2022-09-21 18:01

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.