Learning C++: returning references AND getting around slicing

前端 未结 8 1546
醉酒成梦
醉酒成梦 2021-02-14 00:06

I\'m having a devil of a time understanding references. Consider the following code:

class Animal
{
public:
    virtual void makeSound() {cout << \"rawr\"         


        
8条回答
  •  爱一瞬间的悲伤
    2021-02-14 00:36

    (I'm ignoring your problems with dynamic memory going into references causing memory leaks... )

    Your splitting problems go away when Animal is an abstract base class. That means it has at least one pure virtual method and cannot be directly instantiated. The following becomes a compiler error:

    Animal a = rFunc();   // a cannot be directly instantiated
                          // spliting prevented by compiler!
    

    but the compiler allows:

    Animal* a = pFunc();  // polymorphism maintained!
    Animal& a = rFunc();  // polymorphism maintained!
    

    Thus the compiler saves the day!

提交回复
热议问题