Professional Documents
Culture Documents
ET2031/ ET2031E
Chapter 6: Inheritance
3
6.1. Basic concepts
4
Fundamental principles of OOT
Object-Oriented Technology
Polymorphism
Encapsulation
Abstraction
Inheritance
5
Basic concepts
• Nature of inheritance
• Create a new class by developing an existing class
• The new class inherits what is already in the old class and develops new
features.
• Old class: Parent class, super class, base class
• New class: Child class, sub class, derived class
• Sub class
• is-a-kind-of super class
• Reuse by inheriting data elements and behaviors
of the super class
• Can be detailed to follow new definition
• Extension: Add new properties / behavior
• Redefinition (Method Overriding): Modifying
behavior inherited from the super class
Basic concepts
public:
X() {}
~X() {}
void printX() {}
};
class Y : public X {
int y;
public:
Y() {}
~Y() {}
void printY() {}
};
8
Constructor and Destructor in Inheritance
9
Constructor and Destructor in Inheritance
10
Basic concepts
• Inheritance classification
• Number of base classes:
• Single Inheritance: a sub class inherits only one super class
• Multiple inheritance: a sub class inherits from 2 or more super classes
• Inheritance style:
• private
• protected
• public
• Syntax:
class A {
// members of class A
};
class B : <inheritance_style> A {
// new members of class B
};
Reminder: Access modifier for members of class
12
Inheritance style
• A sub class can inherit from the super class according to the
following styles of inheritance: public, protected, private (default).
• The access scope of the members of the super class changes within
the sub class depending on the style of inheritance.
13
public inheritance style
};
14
public inheritance style
15
public inheritance style
};
16
private inheritance style
class LinkedList {
private: private
... All changes to private, except the
public: private is not accessible
void insertTail(int x) {...}
void insertHead(int x) {...}
void deleteHead() { ... }
void deleteTail() { ... }
int getHead() { ... }
int getTail() { ... }
...
};
Stack s;
class Stack : private LinkedList {
s.push(10);
public:
s.push(20);
void push(int x)
s.pop();
{ insertHead(x); }
int pop() {
s.insertTail(30); // error
int x = getHead(); // error
s.getTail();
deleteHead();
return x;
}
...
};
17
6.2. Polymorphism
18
Polymorphism concept
19
Polymorphism in programming
• Polymorphism in methods:
• Method with the same name, distinguished by list of parameters (method
overloading)
• ...
• Polymorphism in objects:
• Seeing objects in many different ways: one object has the ability to be acted
as other objects
• => An object can perform an action in many different ways
20
Pointer and reference variables to sub class object
class Base{
public:
const char* getName(){ return "Base"; }
};
class Derived : public Base{
public:
const char* getName() { return "Derived"; }
const char* getValueDoubled() { return "Value Doubled"; }
};
int main() derived
{ Inherited
Derived derived; rBase
Base &rBase = derived; members
Base *pBase = &derived; pBase New
cout << "derived is a " << derived.getName() << '\n';
cout << "rBase is a " << rBase.getName() << '\n';
members
cout << "pBase is a " << pBase->getName() << '\n';
return 0;
}
• rBase and pBase are declared as variables of Base class
derived is a Derived • rBase and pBase only "see" the members of the Base class
rBase is a Base • rBase and pBase cannot call getValueDoubled();
pBase is a Base
21
Pointer and reference variables to super class object
class Base{
public:
const char* getName(){ return "Base"; }
};
class Derived : public Base{
public:
int x = 10;
const char* getName() { return "Derived"; }
const char* getValueDoubled() { return "Value Doubled"; }
};
int main()
{
Base base;
Derived derived;
Derived &rDe = base; // error
Derived *pDe = (Derived *)&base;
cout << derived.x << '\n'; 10
cout << pDe->x << '\n'; // unsafe !!!
2661
return 0;
}
22
Polymorphism in methods
void report(Animal *pAnimal){ cout << " says " << pAnimal->speak() << '\n';}
int main()
{
Cat cat;
Dog dog;
Animal *pAnimal = &cat;
report(pAnimal) ; “Early binding” concept
pAnimal = &dog;
report(pAnimal);
return 0; void report(Cat &cat){
} cout << " says " << cat.speak() << '\n';}
? void report(Dog &dog){
cout << " says " << dog.speak() << '\n';}
...
23
Polymorphism in methods
void report(Animal *pAnimal){ cout << " says " << pAnimal->speak() << '\n';}
int main()
{
Cat cat;
Dog dog;
Animal *pAnimal = &cat;
report(pAnimal) ;
pAnimal = &dog;
report(pAnimal)
return 0;
}
24
Virtual method
A a; B b; C c; D d;
a.check();b.check();c.check();d.check();
A *p;
p = &a; p->check(); // A::check();
p = &b; p->check(); // B::check();
p = &c; p->check(); // C::check();
p = &d; p->check(); // B::check();
25
Pure virtual method
26
Abstract class
27
Virtual destructor
28
Layout of an Object With Virtual Function
class X {
int x;
float xx;
static int count;
public:
X() {}
virtual ~X() {}
http://www.vishalchovatiya.com/memory-layout-of-cpp-object/ 29
Layout of an Object With Virtual Function and Inheritance
class X {
int x;
string str;
public:
X() {}
virtual ~X() {}
virtual void printAll() {}
};
class Y : public X {
int y;
public:
Y() {}
~Y() {}
void printAll() {}
};
30
Resume
• Virtual functions ensure that the correct function is called for an object,
regardless of the type of reference (or pointer) used for function call.
• They are mainly used to achieve Runtime polymorphism
• Virtual functions cannot be static or friend function of another class.
• Virtual functions should be accessed using pointer or reference of base class
type to achieve run time polymorphism.
• The prototype of virtual functions should be same in base as well as derived
class.
• It is not mandatory for derived class to override (or re-define the virtual
function), in that case base class version of function is used.
• A class may have virtual destructor but it cannot have a virtual constructor.
31
6.3. Multiple inheritance
32
Multiple inheritance
33
Virtual base class
• A sub class mentioned more than once in a super class can cause
the ambiguity using a virtual base class
class A {
public: int a;
};
class B : public A {};
class C : public A {};
class D : public B, public C {};
D h;
h.a = 1; // error: ambiguity
34
Multiple inheritance
35
Layout of an Object With Virtual Function and Multiple Inheritances
class X {
public:
int x;
virtual ~X() {}
virtual void printX() {}
};
class Y {
public:
int y;
virtual ~Y() {}
virtual void printY() {}
};
36
6.4. Class Design
37
Class Design
• To manage the company's human resources, we can define classes according to the
working positions:
• All 3 classes above have identical properties and functions in terms of content
create an Employee class containing that common information for reuse
38
Class Design
string name;
Super class float salary;
Employee string getName() {...}
void pay() {...}
Sub classes
Worker Manager Director
int level; int dept; void report(){...}
void doWork(){...} void manage(){...}
39
UML - Class diagram
40
UML - Class diagram
41
UML - Class diagram
author
<Person>
Navigability
42
UML - Class diagram
Generalization
43
3.1.1 Symbols in class diagram
https://www.uml-diagrams.org
44
UML - Class diagram
• Example
• Course registration system
Basic classes
45
UML - Class diagram
• Example
• Course registration system
Simple class diagram
LoginForm RegistrationController
RegisterForCoursesForm 1
0..1
1 CloseRegistrationController
0..1
Schedule Professor
CloseRegistrationForm
0..*
0..*
instructor 0..1
1 0..4
Student
Course CourseOffering
0..*
CourseCatalogSystem
BillingSystem
46
UML - Object diagram
Object/instance name
Class name
47
Exercises
1. Viết các lớp Shape (lớp trừu tượng) và các lớp con Circle, Square, Rectangle, Ellipse,
Sphere. Hãy thiết kế việc kế thừa sao cho hợp lý. Viết các hàm ảo tính diện tích hình.
2. Một Company có nhân viên gồm Director, Manager, và Worker. Mỗi nhân viên có tên,
mức lương khác nhau. Viết chương trình thực hiện việc thêm nhân viên, in thông tin
nhân viên, xóa toàn bộ nhân viên.
48
Exercises
1. Write a Shape class (an abstract class) and sub classes named Circle, Square, Rectangle,
Ellipse, Sphere. Design inheritance properly. Write virtual functions that calculate the
area of a shape.
2. A Company has employees consisting of Director, Manager, and Worker. Each employee
has a different name and salary. Write a program to add an array of employees, print
employee information, and delete all employees.
49
50