Why doesn't polymorphism work without pointers/references?

前端 未结 6 1399
萌比男神i
萌比男神i 2020-11-22 03:09

I did find some questions already on SO with similar title- but when I read the answers they were focussing on different parts of the question which were really specific (e.

6条回答
  •  天涯浪人
    2020-11-22 03:48

    I found it really helpful to understand that a copy constructor is invoked when assigning like this:

    class Base { };    
    class Derived : public Base { };
    
    Derived x; /* Derived type object created */ 
    Base y = x; /* Copy is made (using Base's copy constructor), so y really is of type Base. Copy can cause "slicing" btw. */ 
    

    Since y is an actual object of class Base, rather than the original one, functions called on this are Base's functions.

提交回复
热议问题