T
Tony Johansson
Hello!
What does it mean with delegation and can you give me one example.
//Tony
What does it mean with delegation and can you give me one example.
//Tony
Tony said:What does it mean with delegation and can you give me one example.
Tony said:What does it mean with delegation and can you give me one example.
Markus said:Tony Johansson wrote:
Delegation is often an alternative to inheritance.
Suppose you want a special set class that basically behaves like std::set,
and provides the usual functions insert(element), find(), end(). But you
want that insert(element) inserts a *modified* version of the element, e.g.
all-uppercase if the elements are string.
You have two possibilities: inheritance or delegation.
Inheritance:
Make a subclass my_set of std::set and override the insert(element) function
so that it inserts a modified version of the element. (Maybe that's not
even possible if std::set::insert is not virtual).
class my_set : public std::set {
// ...
};
Delegation would be the alternative:
Create you own class my_set, with the member functions insert(element),
find(), end(). It also has a member variable std::set theSet. For the
find() and end() function, you just delegate the calls to theSet! For the
insert(element) function, you modify the element and call
theSet.insert(modifiedElement):
Basically, it looks like this:
class my_set {
public:
// delegate call:
std::set<T>::iterator end(){
return theSet.end();
}
// ... other delegate functions: insert, find
private:
std::set theSet; // delegate all calls to this set object!
};
Delegation is often better than inheritance, for several reasons: You
provide only the functions that are needed, here: insert, find, end. If you
*inherit* you inherit a bunch of other functions whose behavior you don't
know and can't control. std::set might contain other insert functions that
you haven't thought of. If you inherit from std::set your class would have
all these functions, and they do *not* insert a modified version of the
element, as you intended.
Even worse, std::set might change its API (although unlikely for STL
classes, but certainly likely for other classes that you might want to
subclass), adding some different insert() functions, and your subclass
would suddenly be broken! Because those new insert functions would not
insert *modified* versions of the element, which was the point of your
my_set class.
There are more reasons why delegation is better than inheritance, but I
can't remember off the top of my head.
Want to reply to this thread or ask your own question?
You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.