Lecture 17
Lecture 17
Inheritance and
Polymorphism
CS 200
Learning objectives
• Finishing touches
• Operator overloading
• Inheritance
• Polymorphism
• Compile-time
• Run-time
2
Recap
• Why do we use
inheritance?
• It is an object-
oriented way of code
reuse
• Derived classes
inherit the
characteristics of
the base class
• Minimizes redundant
code 3
Methods and Inheritance
• Derived class inherits base class methods and
attributes
• Some methods are not inherited
• Constructors
• Copy constructors
• Destructor
• = operator
• Private methods
• Let’s code!
• A dynamic array that also maintains the largest
value stored
4
Overloading << and >>
void Matrix::operator=(const Matrix& other) {}
6
<< for Complex
• Let’s look at the code example with and without
friend function
7
Other Global Function
Operators
• What if you want to implement > for different
classes?
• Compare a Circle and a Square based on their surface
area
8
Summary
• Stream << and >> operators must be defined
outside the class
• Global or other class member functions may be
declared as friend
• An entire class may be declared as friend
• Friend classes or functions may access this
class’ private or protected members
• Not recommended practice
9
Universal Modelling Language
(UML) Notation
• A diagrammatic way to document object-oriented
design
• Each class is represented as a group of three
rectangles
• Top: Name
• Middle: Attributes (with types) Length
• Bottom: Methods (with argument and return- feet:
types) int
- inches: int int)
• The – symbol indicates private members
+ Length(int,
+
• The + symbol indicates public membersoperator++(Length&)
+ operator
• The # symbol indicates protected members
+(Length&)
…
10
UML Notation for Inheritance
Base
class Base {
protected:
…
public:
…
};
class Derived : public Base {
protected:
… Derived
public:
…
};
11
Upcasting
Base
• Use a base class pointer or
reference for a derived class
object
• Example
• Derived a;
• Base *ptr = &a;
• Example usage: Passing multiple
types of arguments to the same Derived
function
• Slicing: May only access the
What if you have to access derived
base class members through ptr
class members? 12
Slicing
14
Summary
• Upcasting: Storing a derived class reference
(or pointer) in a base class reference (or
pointer)
• You may only access base class members
• Unless you downcasting
• Downcasting: The opposite of upcasting
• Must be done explicitly and is risky
15