我知道关键字virtual
使基类具有多态性,如果我创建一个对象并调用 a virtual function
,将根据运行时分配调用相应的函数,但为什么要创建一个具有不同类型的对象。我是说
Base *ptr = new Derived;
ptr->virtualfunction(); //calls the function which has implemented in Derived class.
如果我创建一个对象
Derived *ptr = new Derived;
ptr->virtualfunction(); // which does the same without the need of making the function virtual.