Why can't I do polymorphism with normal variables?

后端 未结 4 580
忘掉有多难
忘掉有多难 2020-12-04 02:15

I\'m a Java programmer and recently started studying C++. I\'m confused by something.

I understand that in C++, to achieve polymorphic behavior you have to use eithe

4条回答
  •  温柔的废话
    2020-12-04 02:53

    When void printArea(Shape shape) is called, your object is copied into a brand new Shape on the stack. The subclass parts are not copied. This is known as object slicing. If the base-class object is not legit (e.g. it has pure virtual functions in it), you can't even declare or call this function. That's "pass by value" semantics; a copy of the passed-in object is supplied.

    When void printArea(Shape& shape) is called, a reference to your Circle or Rectangle object is passed. (Specifically, a reference to the Shape part of that object. You can't access the Circle- or Square-specific members without casting. But virtual functions work correctly, of course.) That's "pass by reference" semantics; a reference to the original object is passed in.

提交回复
热议问题