C++ overridden function not called

北战南征 提交于 2019-12-02 11:02:36

print is not a virtual function, so you are just relying on static dispatch. This will select the function to call based on the static type of the object, which is obj1in this case.

You should make print virtual:

class obj1{
public:
    virtual void print();
};

Then if you use C++11 you can mark obj2::print as override for safety's sake:

class obj2 : public obj1{
public:
    void print() override;
};

Also note that you never allocate any memory for newobj2.

You should declare print() as virtual to calling obj2::print() for obj2 objects.

virtual void print();
user2692263

I am not entirely sure, it is log time since i did c++, but as I remember You should have the vectors contents be classes with pure virtual functions.

That should force it to look up the right method.

There is a stack overflow answer here, which is slightly related:

Pure Virtual Class and Collections (vector?)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!