The term can be used in different ways in programming. In OOP it's basically a more specific form of aggregation . You leave certain aspects to another class - the delegate - to accomplish what this class - the delegate - needs.
Delegation occurs by having a reference in some member to the other class. It allows you to reuse code manually.
Delegation does not automatically occur with inheritance and polymorphism , but in this case the term does not usually be used.
Only inheritance can be problematic in some cases. And look at that I'm talking about the multiple inheritance that is even more problematic and many languages do not implement it.
Inheritance is often abused and one thinks of reusing the code without correctly conceptualizing the relationship between the more general and specific type. Often reuse can be obtained without inheritance. Of course this will have to be done more manually. On the other hand there is more control and flexibility over reuse.
In fact modern languages did not even have inheritance. This may require a bit more code in some cases by requiring manual delegation, which is what we are talking about here, but they make the language simpler and avoid certain types of problems.
Your example
In your example it shows what I I commented on the previous question . For this class it does not matter how the flight takes place. It is not her responsibility (remembering that classes must have single responsibility, be cohesive ). He takes care of the duck in a general way. The specific flight mechanism is defined in another class. Your class just calls this mechanism.
If it were not for this delegation, besides the class doing more than it needs, it would still have to play a code, which you may not even have access to, in your method. To access the method that actually implements the mechanism you need to have a reference to this class and this is obtained with the variable m_Padrao_Voaveis
.
An interesting detail is that the specific type of this variable has not been defined in this code, so you can use a subtype of Padrao_Voaveis
giving some flexibility to what will actually be executed depending of how this variable is initialized, which can occur within the class itself in configurable or non-configurable form, or externally, that is, a dependency injection .
This can be especially useful when using interfaces. Let's say that the comportamento_pato()
method is part of an interface that you must implement in this class. Give work, take risks writing all the code of this method. But you can have the specific implementation in another class. So you fulfill the contract by defining the method required by the interface but delegate the implementation of the code to what the other class already knows how to do.
Some languages have facilities that automate this delegation a little.