오브젝트 슬라이싱이 뭔가요?

조회수 3469회

어디서 들어봤는데 찾아보니까 안 나와요 object slicing이 뭐에요?

1 답변

  • 좋아요

    0

    싫어요
    채택 취소하기

    슬라이싱은 자식클래스 오브젝트를 부모클래스의 오브젝트에 할당하는겁니다.

    예를들어 다음과 같이 쓰는 경우이지요. Base* baseptr = new Child()

    좀 더 자세히 보겠습니다.

    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(); //가능
        childPtr->printChild(); //가능
    
        basePtr->printBase(); //가능
        //basePtr->printChild(); //불가능
    
    }
    
    childPtr : 0x100100e20, basePtr : 0x100100e20
    print Base
    print Child
    print Base
    Program ended with exit code: 0
    

    basePtr은 분명 childPtr과 같은 객체를 가리키고 있지만 basePtrChild에 대한 정보를 잃어버립니다.

    이와 같이 자식 클래스의 어트리뷰트를 온전히 다 쓸수 없기 때문에 잘려나갔다는 의미에서 slicing이라고 표현 하지요.

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)