CS 330 Lecture 27 – Polymorphism
April 10, 2015 by Chris Johnson. Filed under cs330, lectures, spring 2015.
Agenda
- what ?s
- defining polymorphism
- theorize this
- what does this do?
TODO
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?
show Persuade your neighbor that you are right.
show
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;
}
show
class IntAndDouble {
public:
IntAndDouble() {}
private:
double d;
int i;
};
int main(int argc, char **argv) {
std::cout << sizeof(IntAndDouble) << std::endl;
return 0;
}
show
class TwoIntsAndDouble : public IntAndDouble {
public:
TwoIntsAndDouble() {}
private:
int j;
};
int main(int argc, char **argv) {
std::cout << sizeof(TwoIntsAndDouble) << std::endl;
return 0;
}
show
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;
}
show
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;
}