Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.6k views
in Technique[技术] by (71.8m points)

oop - Polymorphism C++: Passing child object by value to function that accepts parent object

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...