Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of a virtual operator ()() here?

I'm trying to modify code I found, but I'm blocked by my lack of understanding of the purpose, importance, and/or relevance of this virtual operator:

  1. Can someone provide insight as to why this operator is necessary or useful?
  2. Am I right in thinking it takes parentItem(), rect_, and resizer_ as parameters, then modifies the value of resizer_?

Constructor in .h:

virtual void operator()(QGraphicsItem* item, const QRectF& rect) = 0;

Call in .cpp:

(*resizer_)(parentItem(), rect_);

Trimmed context for the constructor for reference:

class SizeGripItem : public QGraphicsItem
{
    private:

        class HandleItem : public QGraphicsRectItem
        {
            public:
                HandleItem(int positionFlags, SizeGripItem* parent);

            private:    
                SizeGripItem* parent_;
        };

    public:
        class Resizer
        {
            public:
                virtual void operator()(QGraphicsItem* item,
                                        const QRectF& rect) = 0;
        };

        SizeGripItem(Resizer* resizer = 0, QGraphicsItem* parent = 0);
        virtual ~SizeGripItem();

    private:
        void doResize();
        QRectF rect_;
        Resizer* resizer_;
};
like image 975
Graeme Rock Avatar asked Mar 11 '23 18:03

Graeme Rock


1 Answers

The Resizer is a broken attempt at a polymorphic functor (function object). Such an idiom was useful before C++11. It's broken because such functors are useless without a virtual destructor. It should have looked as follows:

class Resizer {
public:
  virtual void operator()(QGraphicsItem* item, const QRectF& rect) = 0;
  virtual ~Resizer() {}
};

Such objects are callable:

void invokeResizer(Resizer * resizer, QGraphicsItem * item, const QRectF & rect) {
  (*resizer)(item, rect);
}

The above will execute the method operator()(QGraphicsItem*,const QRectF&) on the resizer object.

In modern code, instead of such hacks, one should use std::function<void(QGraphicsItem*, const QRectF &)>.

like image 76
Kuba hasn't forgotten Monica Avatar answered Mar 13 '23 08:03

Kuba hasn't forgotten Monica