Professional Documents
Culture Documents
Lecture 2
What will we do today?
● Learn more about inheritance,
polymorphism, abstraction,
encapsulation
Mother
Means
daughter
derives from
Mother
Daughter
Tips
● Create a mother class
● Syntax:
class A {
public: A(int x) {}
};
class B: public A {
B(int x) : A(x) {}
};
Exercise: Let’s make shapes!
Write a program that defines a shape class with a constructor that gives
value to width and height. The define two sub-classes triangle and
rectangle, that calculate the area of the shape area ().
In the main, define two variables a triangle and a rectangle and then call
the area() function in this two variables.
Let’s break it down:
1. Make a shape class
2. Add a constructor that takes a width and height
3. Make 2 new classes: triangle and rectangle
4. Add a new method area() to both triangle and rectangle
5. Make a triangle and rectangle in main
6. Display their areas using area() and cout
Destructors
● Destructor is a special class function which destroys the
object as soon as the scope of object ends. The destructor
is called automatically by the compiler when the object goes
out of scope.
Destructors
class A {
public:
};
No overloading allowed!
Problem: Make a Shape(continued)
● Add a destructor for the shape class!
What did we just learn?
● How to make new subclasses using inheritance
● Using destructors
What will Square inherit from?
What will Square inherit from?
Is a Rectangle a Shape?
● Yes
● No
Is a Rectangle a Shape?
● Yes
● No
Is a Rectangle a Triangle?
● Yes
● No
Is a Rectangle a Triangle?
● Yes
● No
What does Derived class inherit from Base class?
● Feature A
● Feature B
● Feature C
● Feature D
What does Derived class inherit from Base class?
If additional time…
● Extend the car class to add extra functions (ex. Drive(), setSpeed(),
convertSpeed())