Beruflich Dokumente
Kultur Dokumente
Inheritances and
Polymorphism
Marco A. León Badillo
1/8
Different kinds
of inheritance
• Public
• Private
• Protected
• Common functionalitiy
• Avoid Code duplication
2/8
Example inheritance
3/8
Constructors and Destructor
Rectangle role in inheritance
Constructor is called when new object is
Shape
created
• Order of constructors:
• First execution in Base class then
Subclass
• Many shapes
5/8
Example polymorphism
6/8
Main Code
int main(void) • Console with virtual function
{
Rectangle r(1, 2, 3.4, 4.5);
Square s(6, 7, 3); Anchor point is: (1,2) length: 3.4 width: 4.5 Area: 15.3
Circle c(4, 2, 4.5); Anchor point is: (6,7) Side: 3 Area: 9
Anchor point is: (4,2) Radius: 4.5 Area: 63.6172
Shape *shape_ptrs[3] = { &r, &s, &c };
unsigned int i;
for (i = 0; i < 3; i++) • Console without virtual function
{
shape_ptrs[i]->print();
at print()
cout << " Area: " << shape_ptrs[i]->
get_area() << endl; Anchor point is: (1,2) Area: 15.3
} Anchor point is: (6,7) Area: 9
} Anchor point is: (4,2) Area: 63.6172
7/8
Pure virtual • Abstract base classes: • Interface classes:
- created by declaring - no object members
functions one or more pure template
(abstract, virtual functions - just pure virtual
interface) - have object members functions
- only
- Pure virtual functions unimplemented
have no real syntax (as methods
it is =0; incomplete). - not possible to
- can't be used to instantiate that
instantiate objects. class
8/8