Delegation
Delegation
(When not to use inheritance)
If you have written almost any non-trival code you have used delegation.
Look at the simple example below and this will become apparent.
The car class delegates request for milage to the
Engine class.
-----------------------------------------------------
class Car{
public:
int getMilage();
private:
Engine hemi;
};
int Car::getMilage(){
return hemi.getMilage();
}
-----------------------------------------------------
The Engine class
-----------------------------------------------------
class Engine{
public:
int getMilage();
};
int Engine::getMilage(){
return 87000;
}
-----------------------------------------------------
A test stub to run it all.
-----------------------------------------------------
int main(){
std::cout<<"main: START\n";
Car aCar;
std::cout<<aCar.getMilage()<<std::endl;
std::cout<<"main: END\n";
return 0;
}
-----------------------------------------------------
Here are the above classes.
c++_delegation.tar