polymorphism 16

polymorphism 16 - Polymorphism Polymorphism Different...

Info iconThis preview shows pages 1–6. Sign up to view the full content.

View Full Document Right Arrow Icon
Polymorphism
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Polymorphism 2 Polymorphism Different objects of the same base class respond differently to the same message. The objects “know” what they are supposed to do without special case program logic. Shape Square Circle Shape* shapes[SHAPES]; shapes[0] = new Square; shapes[1] = new Circle; shapes[2] = new Square; shapes[3] = new Circle; for(j=0; j<SHAPES; ++j) shapes[j]->draw();
Background image of page 2
Polymorphism 3 Interoperability Review Let’s recall the interoperability of base classes and derived objects. class Animal { public: Animal(int legs) : _legs(legs) {} void show() const {cout<<“Legs:”<<_legs<<endl;} void feed() const {cout<<“Animal feeding”<<endl;} private: int _legs; }; class Feline : public Animal{ public: Feline(int legs, int vol) : Animal(legs), purr(vol) {} void show() const {Animal::show(); cout<<“Purr:”<<_purr << endl; } void feed() const {cout<<“Feline feeding”<<endl;} private: int _purr; };
Background image of page 3

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Polymorphism 4 Interoperability Review(cont.) class Canine: public Animal{ public: Canine(int legs,int bark) : Animal(legs), _bark(bark) {} void show() const {Animal::show(); cout<<“Bark:”<<_bark << endl; } void feed() const {cout<<“Canine feeding”<<endl;} private: int _bark; }; void gorge(const Animal& a) { a.feed(); } int main() { Animal a(2);Feline f(4,4);Canine c(4,12); a.feed(); f.feed(); c.feed(); gorge(a); gorge(f); gorge(c); } Output: Animal Feeding Feline Feeding Canine Feeding Animal Feeding Animal Feeding Animal Feeding
Background image of page 4
Polymorphism 5 Compile-time Binding Was the output what you expected? How come we didn’t see polymorphic behavior?
Background image of page 5

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Image of page 6
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 03/17/2010 for the course CS 162 taught by Professor Fant during the Spring '08 term at Portland State.

Page1 / 15

polymorphism 16 - Polymorphism Polymorphism Different...

This preview shows document pages 1 - 6. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online