C++: Vector of objects vs. vector of pointers to new objects?

前端 未结 4 1415
遥遥无期
遥遥无期 2020-12-13 00:33

I am seeking to improve my C++ skills by writing a sample software renderer. It takes objects consisting of points in a 3d space and maps them to a 2d viewport and draws cir

4条回答
  •  醉梦人生
    2020-12-13 01:21

    You wont get what You want with this code

    class World{
        vector object_list;
    public:
        void generate(){
            object_list.clear();
            object_list.push_back(DerivedClass1());
            object_list.push_back(DerivedClass2());
    

    What is going to happen is called object slicing. You will get a vector of ObjectBaseClass.

    To make polymorphism work You have to use some kind of pointers. There are probably some smart pointers or references in boost or other libraries that can be used and make the code much safer than the second proposed solution.

提交回复
热议问题