Does downcasting defeat the purpose of polymorphism?

前端 未结 4 825
暖寄归人
暖寄归人 2021-01-01 16:52

I encountered a question today, found here, which raised this question for me.

Here\'s a pseudo-code example of what I\'m getting at:

class Car{
publ         


        
4条回答
  •  悲&欢浪女
    2021-01-01 17:39

    Yes, this is usually the better design case. You should only introduce a virtual function into the hierarchy if it makes sense for all derived classes.

    However, your MODEL enum is completely worthless- that's what dynamic_cast is actually for.

    if(Lamborghini* lambo = dynamic_cast(cars[i])) {
        lambo->retractTheRoof();
    }
    

提交回复
热议问题