I am using the Direct2D API to draw some graphics for my program. I have a function that I call every time the Window redraws that draws the frame. I can't hardcode every object to be drawn into the function, if I want it to be dynamic. What is the common practice for solving this?

7 Years
Discussion Span
Last Post by mike_2000_17

Again, polymorphism comes to the rescue. It is extremely typical, in fact I don't remember ever seeing any other solution to this, to use a "renderable" interface class and make all your objects that need to be rendered as derived from that interface:

//interface for all renderable objects
class Renderable {
    virtual void render() = 0; //pure virtual render method.

//say you have a class Square, which is derived from another class Polygon, derive it also from interface class Renderable
class Square : public Polygon, public Renderable {
    void render() { ..put rendering code here.. };

//Say you have a Canvas class that holds all things that are rendered to the screen or window:
class Canvas {
    std::vector<Renderable*> Objects; //hold the list of renderable objects.
    void render() { //Canvas has its own render function, of course.
      ... initialize screen (like clear buffer, load camera, etc.) ...
      for(int i=0;i<Objects.size();++i)
          Objects[i]->render(); //render all the objects.
      ... finish off ...

I have programmed several game engines and other visualization stuff, and that's basically the way to go, most of the time (at least in simple cases).

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.