Back to notes -- Keyboard shortcut: 'u'        next -- Keyboard shortcut: 'n'  Slide program -- Keyboard shortcut: 't'    Illustration of object slicing.Lecture 4 - slide 3 : 24
Program 1
// Class B inherits from A. 
// Illustration of slicing when we copy B object to a variable of static type A.

#include <iostream>
#include <string>

using namespace std;

class A {
public:
  int a;

  A(): a(3){
  }

  virtual int op(){
     cout << "A: operation" << endl;
     return a;
  }
};

class B: public A {
public:
  int b;

  B():  b(5){
  }

  int op(){
     cout << "B: operation" << endl;
     return b;
  }
};

int f(B &x){
  A  y = x,        // The B object x is sliced: The B part is lost during copy construction.
    *z = &x,       // No slicing. The B object is accessed via pointer.
    &w = x;        // No slicing. The B object is accessed via a reference.

  cout << y.op() << endl;    // 3.  A operation. y has been sliced to an A object.
  cout << z->op() << endl;   // 5.  B operation. z points at a B object.
  cout << w.op() << endl;    // 5.  B operation. w is an alias to aB from main.
}

int main(){
  B aB;
  f(aB);
}