c++dynamicpolymorphismheterogeneous

Alternative to dynamic polymorphisme C++



Consider the following polymorphisme case:
class Shape {
public:
   Shape();
   virtual void draw() = 0;
   virtual ~Shape();
}

class Triangle : public Shape {
public:
   Triangle();
   void draw();
   ~Triangle();
}

class Square : public Shape {
public:
   Square();
   void draw();
   ~Square();
}

class Circle : public Shape {
public:
   Circle();
   void draw();
   ~Circle();
}

class Container {
   public:
       void addShape(string type); //Create and add instance of selected type to render_list
       void render(); //iterate through render_list and draw() each object
   private:
       vector<Shape*> render_list;
}

If render() method is called at very fast rate, is this a good way of implementing an heterogenous collection ?
Will the vtable use be a problem for performance ?
Is there any alternative ?


Solution

  • is this a good way of implementing an heterogenous collection ?

    It will work, but I wouldn't call it a good way. The problem is that your vector uses raw pointers (Shape*) and it could lead to memory leaks. Prefer to use containers of smart pointers, i.e. std::vector<std::unique_ptr<Shape>>, instead of raw ones std::vector<Shape*>.

    Will the vtable use be a problem for performance ?

    The performance hit will be negligible. This is the very correct usage of polymorphism.

    Is there any alternative ?

    Yes, there are a lot of them. From enums, through additional pointes and/or unions. Are they better than this one? I wouldn't say so. Each has it's own pros and cons, but your approach is probably the most readable one, which is an extremely important factor when writing code.

    The additional problem for the alternatives is the fact that "none of them would be able to keep the code separation without the same sacrifices to indirection" (thanks @SoronelHaetir).