C++: Overridden overloads problem (error C2660)

For the first time today I hit the case where method in the concrete class overrides method in the base class. For example:

typedef unsigned int Color;
 
class Widget
{
public:
  // Template method to draw
  void Draw() const
  {
    // compute stuff
    const Color yourFavoriteColor = 0x424242FF;
    // draw concrete
    Draw( yourFavoriteColor );
  }
  virtual void Draw(const Color color) const = 0;
};
 
class UberWidget : public Widget
{
protected:
  virtual void Draw(const Color color) const override
  {
    // draw the uber widget
  }
};
 
int _tmain(int argc, _TCHAR* argv[])
{
  UberWidget widget;
 
  // error C2660: 'UberWidget::Draw' : 
  // function does not take 0 arguments
  widget.Draw(); << doesn't compile!
 
  return 0;
}

If you comment the Draw() call and look at the vtable of the object you can see that you don’t have two methods:

So the solution is to use

  widget.Widget::Draw();

Or in my opinion a better solution is to use a different method name, like using the prefix “On*” for the overloaded method:

class Widget
{
public:
  // Template method to draw
  void Draw() const
  {
    // compute stuff
    const Color yourFavoriteColor = 0x424242FF;
    // draw concrete
    OnDraw( yourFavoriteColor );
  }
protected:
  virtual void OnDraw(const Color color) const = 0;
};
 
class UberWidget : public Widget
{
protected:
  virtual void OnDraw(const Color color) const override
  {
    // draw the uber widget
  }
};
 
int _tmain(int argc, _TCHAR* argv[])
{
  UberWidget widget;
  widget.Draw(); // Works fine!
  return 0;
}
This entry was posted in C++, Coding and tagged , . Bookmark the permalink.

2 Responses to C++: Overridden overloads problem (error C2660)

  1. tvorez says:

    Try “using Widget::Draw;”, like this:
    ————————————–

    typedef unsigned int Color;

    class Widget
    {
    public:
    // Template method to draw
    void Draw() const
    {
    // compute stuff
    const Color yourFavoriteColor = 0x424242FF;
    // draw concrete
    Draw( yourFavoriteColor );
    }
    virtual void Draw(const Color color) const = 0;
    };

    class UberWidget : public Widget
    {
    protected:
    using Widget::Draw;

    virtual void Draw(const Color color) const override
    {
    // draw the uber widget
    }
    };

    int _tmain(int argc, _TCHAR* argv[])
    {
    UberWidget widget;

    widget.Draw(); << doesn't compile!

    return 0;
    }

  2. Jonathan says:

    Good point. Thanks for the reply.

Leave a Reply

Your email address will not be published. Required fields are marked *