In this variant of the program, the aB object from main is sliced already when it is passed to f.
Therefore, x in f refers to an instance of class A. Both via y, z, and w, op() returns the value of a from clas A. Namely 3. Here is my solution, with some comments:// Class B inherits from A. Illustration of slicing.
// A minor variant of the previous program.
#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(A x){ // Was int f(B &x) in the original version. Now the parameter is passed by value. Sliced during parameter passing.
A y = x,
*z = &x,
&w = x;
cout << y.op() << endl; // 3. A operation. y is an A object (sliced when passed to f).
cout << z->op() << endl; // 3. z is a pointer to an instance of A.
cout << w.op() << endl; // 3. z is a reference to an instance of A.
// So did anything change? YES - A LOT
}
int main(){
B aB;
f(aB);
}