Overriding vs Virtual

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

    This is the classic question of how polymorphism works I think. The main idea is that you want to abstract the specific type for each object. In other words: You want to be able to call the Child instances without knowing it's a child!

    Here is an example: Assuming you have class "Child" and class "Child2" and "Child3" you want to be able to refer to them through their base class (Parent).

    Parent* parents[3];
    parents[0] = new Child();
    parents[1] = new Child2();
    parents[2] = new Child3();
    
    for (int i=0; i<3; ++i)
        parents[i]->say();
    

    As you can imagine, this is very powerful. It lets you extend the Parent as many times as you want and functions that take a Parent pointer will still work. For this to work as others mention you need to declare the method as virtual.

提交回复
热议问题