- 24. Subtyping, Inheritance and
Polymorphism
Expression Trees, Separation of Concerns and Modularisation, Type Hierarchies, Virtual Functions, Dynamic Binding, Code Reuse, Concepts of Object-Oriented Programming
750
24. Subtyping, Inheritance and Polymorphism Expression Trees, - - PowerPoint PPT Presentation
24. Subtyping, Inheritance and Polymorphism Expression Trees, Separation of Concerns and Modularisation, Type Hierarchies, Virtual Functions, Dynamic Binding, Code Reuse, Concepts of Object-Oriented Programming 750 Last Week: Expression Trees
750
751
struct tnode { char op; // Operator (’=’ for literals) double val; // Literal’s value tnode* left; // Left child (or nullptr) tnode* right; // ... ... };
+ ⋆ = 2 ⋆ ⋆ ∗ ⋆
Value left operand right operand ⋆: unused
752
753
754
755
756
1 + size(left operand) + size(right operand)
757
758
Exp BinExp Times
759
Exp BinExp Times
1derived class, child class 2base class, parent class 760
Activates dynamic dispatch Enforces implementation by de- rived classes ... ...that makes Exp an abstract class
Literal inherits from Exp ... ...but is otherwise just a regular class
761
762
763
764
765
Note: BinExp does not implement eval and is therefore also an abstract class, just like Exp
766
Addition inherits member vari- ables (left, right) and functions (size) from BinExp
Calling the super constructor (con- structor of BinExp) initialises the member variables left and right
767
Observation: Additon::eval() and Times::eval() are very similar and could also be unified. However, this would require the concept of functional programming, which is outside the scope of this course.
768
769
struct tnode { char op; double val; tnode* left; tnode* right; ... } double eval(const tnode* n) { if (n->op == ’=’) return n->val; double l = 0; if (n->left != 0) l = eval(n->left); double r = eval(n->right); switch(n->op) { case ’+’: return l + r; case ’*’: return l - r; case ’-’: return l - r; case ’/’: return l / r; default: // unknown operator assert (false); } } int size (const tnode* n) const { ... } ... struct Literal : public Exp { double val; ... double eval() const { return val; } }; struct Addition : public Exp { ... double eval() const { return left->eval() + right->eval(); } }; struct Times : public Exp { ... double eval() const { return left->eval() * right->eval(); } } struct Cos : public Exp { ... double eval() const { return std::cos(argument->eval()); } }
770
771
772
773
774
775
776
M motivating example for each chapter C
L
E
777
778
M
C
L
779
M
C
L
E
780
C
L
a && !b
E
781
C
L
E
782
M
C
L
while (n > 1) {...}
if (a < 0) continue;
E
783
M
C
L
E
784
M
C
L
double pow(double b, int e){ ... }
E
785
M
C
L
E
786
M
C
L
E
787
M
C
E
788
M
C
L
E
789
M
C
L
E
790
M
C
L
const int *a; E
791
M
C
L
std::fill (a, a+5, 1);
E
792
M
C
L
E
793
M
C
L
E
794
795