C++ - Inheritances
C++ - Inheritances
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
• Aggregation:
• A binary association between whole object and part object. 1 4
• "has-a" relationship (or “is-a-part-of” relationship) TuGiac Diem
• part instance is independent of the whole instance.
• Example:
• A quadrangle : includes 4 points Use point definition to define a quadrangle
• Composition:
• A "strong" form of aggregation
• a part could be included in at most one composite (whole) at a time
• if a whole is deleted, all of its parts are "normally" deleted with.
7
Aggregation - Composition
class Diem {
private: int x, y;
public:
Diem(){}
Diem(int x, int y) { this->x = x; this->y = y;}
void setX(int x){ this->x = x; }
int getX() { return x; }
void printDiem(){ cout << "(" << x << ", " << y << ")" << endl; }
};
1 4
1
TuGiac Diem
class TuGiac { 4
TuGiac Diem class TuGiac {
private: Diem d1, d2, d3, d4; private:
public: Diem d1, d2, d3, d4;
TuGiac(Diem p1, Diem p2, public:
Diem p3, Diem p4){ TuGiac(){
d1 = p1; d2 = p2; d3 = p3; d4 = p4; d1 = Diem(); d2 = Diem(0,1);
} d3 = Diem (1,1); d4 = Diem (1,0);
void printTuGiac(){ }
d1.printDiem(); d2.printDiem(); void printTuGiac(){
d3.printDiem(); d4.printDiem(); d1.printDiem(); d2.printDiem();
} d3.printDiem(); d4.printDiem();
}; }
};
8
Inheritance
• 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
class X {
int x;
string str;
new attributes
public:
X() {}
~X() {}
void printX() {}
};
class Y : public X {
int y;
Y class object can call
public:
this inherited method
Y() {}
~Y() {}
void printY() {} new methods
};
10
Constructor and Destructor in Inheritance
11
Constructor and Destructor in Inheritance
12
Reminder: Access modifier for members of class
13
Inheritance style
• 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
};
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.
15
public inheritance style
};
16
public inheritance style
17
public inheritance style
};
18
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;
}
...
};
19
6.2. Polymorphism
20
Polymorphism concept
21
Polymorphism in programming
• Polymorphism in methods:
• Method with the same name, distinguished by list of parameters (method
overloading)
• Make different solutions using the same prototype (virtual method)
• ...
• 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
22
Pointer and reference variables to sub class object
class Base{ derived
public:
const char* getName(){ return "Base"; } Inherited
rBase
}; members
class Derived : public Base{ pBase
public:
New
int x = 10;
Overriding method members
const char* getName() { return "Derived"; }
const char* getValueDoubled() { return "Value Doubled"; }
};
int main(){
Derived derived; • rBase and pBase are declared as
Base &rBase = derived; variables of Base class
Base *pBase = &derived; • rBase and pBase only "see" the
cout << derived.x<< '\n'; 10 members of the Base class
cout << rBase.x<< '\n'; // error
cout << pBase->x<< '\n'; // error
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';}
need to add more functions? void report(Dog &dog){
cout << " says " << dog.speak() << '\n';}
...
25
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;
}
26
Virtual method
A a; B b; C c; D d;
a.check();b.check();c.check();d.check(); ABCB
A *p;
p = &a; p->check(); // A::check();
p = &b; p->check(); // B::check();
ABCB // C::check();
p = &c; p->check();
p = &d; p->check(); // B::check();
27
Pure virtual method
28
Abstract class
29
Virtual destructor
30
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/ 31
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() {}
};
32
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.
33
6.3. Multiple inheritance
34
Multiple inheritance
35
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
36
Multiple inheritance
37
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() {}
};
38
6.4. Class Design
(READ AT HOME)
39
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
40
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(){...}
41
UML - Class diagram
42
UML - Class diagram
43
UML - Class diagram
author
<Person>
Navigability
44
UML - Class diagram
Generalization
45
3.1.1 Symbols in class diagram
https://www.uml-diagrams.org
46
UML - Class diagram
• Example
• Course registration system
Basic classes
47
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
48
UML - Object diagram
Object/instance name
Class name
49
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.
50
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.
51