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?
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…