Overriding vs Virtual

前端 未结 8 671
星月不相逢
星月不相逢 2020-12-04 18:10

What is the purpose of using the reserved word virtual in front of functions? If I want a child class to override a parent function, I just declare the same function such as

8条回答
  •  旧巷少年郎
    2020-12-04 18:30

    If the function were virtual, then you could do this and still get the output "2":

    Parent* a = new Child();
    a->say();
    

    This works because a virtual function uses the actual type whereas a non-virtual function uses the declared type. Read up on polymorphism for a better discussion of why you'd want to do this.

提交回复
热议问题