Overriding vs Virtual

前端 未结 8 685
星月不相逢
星月不相逢 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:27

    Try it with:

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

    Without virtual, both with print '1'. Add virtual, and the child will act like a Child, even though it's being referred to via a pointer to a Parent.

提交回复
热议问题