-1

I am passing a child object by value to a function that accepts a parent object. I did not expected to work because I thought that polymorphism involving upcasting applied only for pointers/references.

class A
{
public:
  int x;
  A() :x{ 5 } {}
};

class B : public A
{
public:
  int y;

  B() :y{ 5 } { x = 10; }
};

void foo(A a)
{
  cout << a.x << endl;
}

int main()
{
  A a;
  B b;

  // it works to send b to foo
  // foo will print value 10
  foo(b);
}

It seems that foo will print value 10 i.e the x value from the child class. Can somebody help me understand what is happening please?

Paul Sanders
  • 24,133
  • 4
  • 26
  • 48
Vasi Marin
  • 453
  • 1
  • 3
  • 9

1 Answers1

2

Although passing b to foo will involve object slicing, that doesn't affect the value of b.x as seen by foo since that was set when the object was constructed. You just sliced away b.y, which has no effect in the code as written.

Paul Sanders
  • 24,133
  • 4
  • 26
  • 48