CS 330 Lecture 27 – Polymorphism
Agenda
- what ?s
- defining polymorphism
- theorize this
- what does this do?
TODO
- 1/4 sheet: Read http://www.insomniacgames.com/tech/articles/0308/three_big_lies.php. (This page rendered improperly for me; I had to highlight the text to read it.) Read http://hacksoflife.blogspot.com/2008/04/what-is-oop-good-for.html. What do you think?
Intentions
- I can define polymorphism and identify the benefits it confers upon developers like me.
- I can comprehend how dynamic dispatch provides for polymorphic behavior.
- I can describe several possible ways of implementing dynamic dispatch.
Theorize This
On your own, generate a theory for how dynamic dispatch might work? Given a reference/pointer to a supertype, how is it that we end up calling the right method in the subtype?
Persuade your neighbor that you are right.
What Does This Do?
#include <iostream> class Super { public: void print() { std::cout << "in super" << std::endl; } }; class Sub : public Super { public: void print() { std::cout << "in sub" << std::endl; } }; int main(int argc, char **argv) { Sub a; a.print(); Super b; b.print(); Super *c = new Sub(); c->print(); delete c; return 0; }
class IntAndDouble { public: IntAndDouble() {} private: double d; int i; }; int main(int argc, char **argv) { std::cout << sizeof(IntAndDouble) << std::endl; return 0; }
class TwoIntsAndDouble : public IntAndDouble { public: TwoIntsAndDouble() {} private: int j; }; int main(int argc, char **argv) { std::cout << sizeof(TwoIntsAndDouble) << std::endl; return 0; }
class IntAndDouble { public: IntAndDouble() {} virtual int Get() const { return i; } private: double d; int i; }; class TwoIntsAndDouble : public IntAndDouble { public: TwoIntsAndDouble() {} virtual int Get() const { return j; } private: int j; }; int main(int argc, char **argv) { std::cout << sizeof(IntAndDouble) << std::endl; std::cout << sizeof(TwoIntsAndDouble) << std::endl; return 0; }
A Virtual Class
class A {
virtual void f();
virtual void g(int);
virtual void h(double);
int a;
}
class B : public A {
void g(int); // overrides A::g
virtual void m(B *);
int b;
}
class C : public B {
void h(double); // overrides A::h
virtual void n(C *);
int c;
}