13.01.2015 Views

Pensar en C++ (Volumen 1) - Grupo ARCO

Pensar en C++ (Volumen 1) - Grupo ARCO

Pensar en C++ (Volumen 1) - Grupo ARCO

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

✐<br />

✐<br />

✐<br />

“Volum<strong>en</strong>1” — 2012/1/12 — 13:52 — page 459 — #497<br />

✐<br />

15.9. Sobrecargar y redefinir<br />

class Pet {<br />

public:<br />

virtual string type() const = 0;<br />

virtual PetFood* eats() = 0;<br />

};<br />

class Bird : public Pet {<br />

public:<br />

string type() const { return "Bird"; }<br />

class BirdFood : public PetFood {<br />

public:<br />

string foodType() const {<br />

return "Bird food";<br />

}<br />

};<br />

// Upcast to base type:<br />

PetFood* eats() { return &bf; }<br />

private:<br />

BirdFood bf;<br />

};<br />

class Cat : public Pet {<br />

public:<br />

string type() const { return "Cat"; }<br />

class CatFood : public PetFood {<br />

public:<br />

string foodType() const { return "Birds"; }<br />

};<br />

// Return exact type instead:<br />

CatFood* eats() { return &cf; }<br />

private:<br />

CatFood cf;<br />

};<br />

int main() {<br />

Bird b;<br />

Cat c;<br />

Pet* p[] = { &b, &c, };<br />

for(int i = 0; i < sizeof p / sizeof *p; i++)<br />

cout type() foodType() upcast de BirdFood a PetFood<br />

<strong>en</strong> el retorno de la función.<br />

Pero <strong>en</strong> Cat, el tipo devuelto por eats() es un puntero a CatFood, que es un<br />

tipo derivado de PetFood. El hecho de que el tipo de retorno esté heredado del tipo<br />

459<br />

✐<br />

✐<br />

✐<br />

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!