Polymorphism Polymorphism From Greek , polys, "many, - - PowerPoint PPT Presentation

polymorphism polymorphism
SMART_READER_LITE
LIVE PREVIEW

Polymorphism Polymorphism From Greek , polys, "many, - - PowerPoint PPT Presentation

Polymorphism Polymorphism From Greek , polys, "many, much" and , morph, "form, shape." The ability for a derived


slide-1
SLIDE 1

Polymorphism ¡

slide-2
SLIDE 2

Polymorphism ¡

  • From ¡Greek ¡πολύς, ¡polys, ¡"many, ¡much" ¡and ¡

μορφή, ¡morphē, ¡"form, ¡shape." ¡ ¡

  • The ¡ability ¡for ¡a ¡derived ¡class ¡to ¡subs3tute ¡in ¡

code ¡where ¡a ¡base ¡class ¡is ¡used. ¡

slide-3
SLIDE 3
  • This ¡concept ¡is ¡not ¡new: ¡

void ¡f(double ¡x) ¡{ ¡ ¡ ¡ ¡/* ¡do ¡something ¡*/; ¡ ¡ } ¡ ¡ int ¡main() ¡{ ¡ ¡ ¡int ¡y ¡= ¡3; ¡ ¡ ¡f(y); ¡ } ¡

¡

slide-4
SLIDE 4

C++ ¡will ¡automa,cally ¡convert ¡a ¡derived ¡class ¡

  • bject ¡to ¡a ¡base ¡class ¡object ¡when ¡required. ¡

¡ Typical ¡situaGons: ¡

  • Variable ¡assignment ¡
  • Calling ¡a ¡funcGon ¡
slide-5
SLIDE 5

Caveat ¡emptor ¡

  • When ¡C++ ¡automaGcally ¡converts ¡a ¡derived-­‑

class ¡object ¡to ¡a ¡base-­‑class ¡object, ¡the ¡ converted ¡object ¡loses ¡all ¡extra ¡abiliGes ¡the ¡ derived ¡class ¡had. ¡

slide-6
SLIDE 6

class ¡A ¡{ ¡ ¡ ¡ ¡public: ¡ ¡ ¡ ¡void ¡f() ¡{ ¡cout ¡<< ¡"base ¡f"; ¡} ¡ }; ¡ class ¡B ¡: ¡public ¡A ¡{ ¡ ¡ ¡public: ¡ ¡ ¡void ¡f() ¡{ ¡cout ¡<< ¡"derived ¡f"; ¡} ¡ ¡ ¡void ¡g() ¡{ ¡cout ¡<< ¡"derived ¡g"; ¡} ¡ }; ¡ int ¡main() ¡{ ¡ ¡ ¡A ¡a; ¡ ¡a.f(); ¡ ¡ ¡B ¡b; ¡ ¡b.f(); ¡ ¡b.g(); ¡ ¡ ¡A ¡copy ¡= ¡b; ¡ ¡copy.f(); ¡ ¡copy.g(); ¡ } ¡

slide-7
SLIDE 7

Caveat ¡emptor ¡

  • When ¡C++ ¡automaGcally ¡converts ¡a ¡derived-­‑

class ¡object ¡to ¡a ¡base-­‑class ¡object, ¡the ¡ converted ¡object ¡loses ¡all ¡extra ¡abiliGes ¡the ¡ derived ¡class ¡had. ¡

  • Copying ¡the ¡derived-­‑class ¡object ¡into ¡a ¡base-­‑

class ¡object ¡means ¡the ¡copy ¡only ¡has ¡the ¡ abiliGes ¡of ¡the ¡base ¡class. ¡

  • How ¡do ¡we ¡avoid ¡making ¡copies? ¡
slide-8
SLIDE 8

Step ¡1: ¡Use ¡Pointers ¡

  • A ¡base-­‑class ¡pointer ¡can ¡point ¡to ¡a ¡derived-­‑

class ¡object. ¡

  • Because ¡no ¡copy ¡is ¡made, ¡the ¡pointer ¡sGll ¡

points ¡at ¡an ¡object ¡that ¡has ¡all ¡the ¡abiliGes ¡of ¡ the ¡derived ¡class. ¡

  • The ¡base-­‑class ¡pointer ¡will ¡sGll ¡only ¡let ¡you ¡

(directly) ¡call ¡funcGonality ¡specified ¡by ¡the ¡ base ¡class. ¡

slide-9
SLIDE 9

Step ¡2: ¡Use ¡virtual ¡methods ¡

  • Class ¡methods ¡can ¡be ¡tagged ¡with ¡the ¡

keyword ¡"virtual." ¡

  • When ¡a ¡virtual ¡method ¡is ¡called ¡using ¡a ¡

pointer, ¡C++ ¡uses ¡the ¡version ¡of ¡the ¡method ¡ that ¡belongs ¡to ¡the ¡type ¡of ¡the ¡object ¡being ¡ pointed ¡at, ¡not ¡the ¡type ¡of ¡the ¡pointer. ¡