In OOP, what is forwarding and how is it different from delegation?

后端 未结 3 702
终归单人心
终归单人心 2021-02-02 11:21

Would someone please explain the difference between forwarding and delegation? They seem similar, but I haven\'t been able to find a good definition of forwarding, so I\'m not s

3条回答
  •  一整个雨季
    2021-02-02 11:34

    Forwarding is sort of like "inheritance via containment", or "implementation inheritance the hard way".

    Typical implementation inheritance:

    class Base
    {
     public:
        void baseFn() { }
    };
    
    class Derived : public Base
    {
     public:
        void derivedFn() { }
    };
    

    Now, an instance of Derived has a baseFn() method. This is a way of sharing implementation between different classes.

    Forwarding looks like this:

    class Contained
    {
     public:
        void containedFn() { }
    };
    
    class Thing
    {
     public:
        void thingFn() { }
        void containedFn() { mContained.containedFn(); }
     private:
        Contained mContained;
    };
    

    You could have also implemented that with private inheritance.

    Delegation is a special case of forwarding, where at the "thing to forward" to is an interface itself.

    class Delegate
    {
     public:
        virtual void doDelegateAction() = 0;
    };
    
    class DelegateA : public Delegate
    {
        virtual void doDelegateAction() { }
    };
    
    class DelegateB : public Delegate
    {
        virtual void doDelegateAction() { }
    };
    
    class Thing
    {
     public:
        void Thing (Delegate * delegate) { mDelegate = delegate; }
        void thingFn() { }
        void containedFn() { if (mDelegate) mDelegate->doDelegateAction(); }
     private:
        Delegate * mDelegate; // Note, we don't own this memory, buyer beware.
    };
    

    Now, you can swap out the implementation of delegate at runtime, whereas in forwarding you cannot (and you may not want to, which is why you would do it).

    If that answers the wrong question, let me know in a comment and I'll remove the answer.

提交回复
热议问题