简体   繁体   中英

Slicing vs Upcasting :: Is my understanding correct?

Let A be the base class and B be it's publicly derived class.

B b;

Slicing:

A a = b; 

Upcasting:

A* p = &b; // p is a pointer variable of type A
A& r = b; // r is a reference variable of type A

Is this correct? Please share similar examples to illustrate the two concepts if possible.

Yes!

Object slicing happens when a derived class object is assigned to a base class object, additional attributes of a derived class object are sliced off to form the base class object.

So yes, if you have a base class A

class A{
  public:
    int x;
    char y;
};

and a class B derived publically from A with some extra data members,

class B:public A{
  public:
    int z;
};

doing A a = b; will slice off 'z'.

Upcasting is conversion of pointer or reference of derived class type to pointer or reference of base class type, going up in the inheritance tree.

B objB;
A *objA = &objB;

Just to bring more light on this subject, you can convert a base-class pointer(reference) to a derived-class pointer (reference).It is called downcasting (opposite to upcasting).

B *objB = (B *) &A;

But there's no way you can assign a base class object to a derived class object.

Cheers!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM