SlideShare a Scribd company logo
1 
Inheritance and Polymorphism 
Andrew Davison 
Noppadon Kamolvilassatian 
Department of Computer Engineering 
Prince of Songkla University
2 
Contents 
1. Key OOP Features 
2. Inheritance Concepts 
3. Inheritance Examples 
4. Implementing Inheritance in C++ 
5. Polymorphism 
6. Inclusion (Dynamic Binding) 
7. Virtual Function Examples 
8. C++ Pros and Cons
3 
1. Key OOP Features 
ADTs (done in the last section) 
Inheritance 
Polymorphism
4 
2. Inheritance Concepts 
Derive a new class (subclass) from an existing class (base class or superclass). 
Inheritance creates a hierarchy of related classes (types) which share code and interface.
5 
3. Inheritance Examples 
Base ClassDerived ClassesStudentCommuterStudentResidentStudentShapeCircleTriangleRectangleLoanCarLoanHomeImprovementLoanMortgageLoan
6 
More Examples 
Base ClassDerived ClassesEmployeeManagerResearcherWorkerAccountCheckingAccountSavingAccount
7 
University community members 
Employee 
CommunityMember 
Student 
Faculty 
Staff 
Administrator 
Teacher
8 
Shape class hierarchy 
TwoDimensionalShape 
Shape 
ThreeDimensionalShape 
Circle 
Square 
Triangle 
Sphere 
Cube 
Tetrahedron
9 
Credit cards 
logo 
american express 
hologram 
card 
owner’s name 
inherits from (isa) 
visa card 
master card 
pin 
category
10 
4. Implementing Inheritance in C++ 
Develop a base class called student 
Use it to define a derived class called grad_student
11 
The Student Class Hierarchy 
student 
print() year_group() 
grad_student 
print() 
inherits (isa) 
student_id, year, name 
dept, thesis
12 
Student Class 
class student { public: student(char* nm, int id, int y); void print(); int year_group() { return year; } private: int student_id; int year; char name[30]; };
13 
Member functions 
student::student(char* nm, int id, int y) { student_id = id; 
year = y; 
strcpy(name, nm); } void student::print() { cout << "n" << name << ", " << student_id << ", " << year << endl; }
14 
Graduate Student Class 
class grad_student: public student { public: grad_student(char* nm, int id, int y, char* d, char* th); void print(); private: char dept[10]; char thesis[80]; };
15 
Member functions 
grad_student::grad_student(char* nm, int id, int y, char* d, char* th) :student(nm, id, y) { strcpy(dept, d); strcpy(thesis, th); } void grad_student::print() { student::print(); cout << dept << ", " << thesis << endl; }
16 
Use 
int main() { student s1("Jane Doe", 100, 1); grad_student gs1("John Smith", 200, 4, "Pharmacy", "Retail Thesis"); cout << "Student classes example:n"; cout << "n Student s1:"; s1.print(); cout << “Year “ << s1.year_group() << endl; : 
continued
17 
cout << "n Grad student gs1:"; gs1.print(); cout << “Year “ << gs1.year_group() << endl; :
18 
Using Pointers 
student *ps; grad_student *pgs; ps = &s1; cout << "n ps, pointing to s1:"; ps->print(); ps = &gs1; cout << "n ps, pointing to gs1:"; ps->print(); pgs = &gs1; cout << "n pgs, pointing to gs1:"; pgs->print(); return 0; }
19 
Output 
$ g++ -Wall -o gstudent gstudent.cc $ gstudent Student classes example: Student s1: Jane Doe, 100, 1 Year 1 Grad student gs1: John Smith, 200, 4 Pharmacy, Retail Thesis Year 4 : 
continued
20 
ps, pointing to s1: Jane Doe, 100, 1 ps, pointing to gs1: John Smith, 200, 4 pgs, pointing to gs1: John Smith, 200, 4 Pharmacy, Retail Thesis $ 
student print() used. 
grad_student print() used.
21 
Notes 
The choice of print() depends on the pointer type, not the object pointed to. 
This is a compile time decision (called static binding).
22 
5. Polymorphism 
Webster: "Capable of assuming various forms." 
Four main kinds: 
1. coercion 
a / b 
2. overloading 
a + b 
continued
23 
3. inclusion (dynamic binding) 
–Dynamic binding of a function call to a function. 
4. parametric 
–The type argument is left unspecified and is later instantiated 
e.g generics, templates
24 
6. Inclusion (dynamic binding) 
5.1. Dynamic Binding in OOP 
5.2. Virtual Function Example 
5.3. Representing Shapes 
5.4. Dynamic Binding Reviewed
25 
Dynamic Binding in OOP 
X 
print() 
Classes 
Y 
print() 
Z 
print() 
inherits (isa) 
X x; Y y; Z z; X *px; px = & ??; // can be x,y,or z px->print(); // ??
26 
Two Types of Binding 
Static Binding (the default in C++) 
–px->print() uses X’s print 
–this is known at compile time 
Dynamic Binding 
–px->print() uses the print() in the object pointed at 
–this is only known at run time 
–coded in C++ with virtual functions
27 
Why “only known at run time”? 
Assume dynamic binding is being used: X x; Y y; Z z; X *px; : cin >> val; if (val == 1) px = &x; else px = &y; px->print(); // which print() is used?
28 
7. Virtual Function Examples 
class B { public: int i; virtual void print() { cout << "i value is " << i << " inside object of type Bnn"; } }; class D: public B { public: void print() { cout << "i value is " << i << " inside object of type Dnn"; } };
29 
Use 
int main() { B b; B *pb; D d; // initilise i values in objects b.i = 3; d.i = 5; :
30 
pb = &b; cout << "pb now points to bn"; cout << "Calling pb->print()n"; pb->print(); // uses B::print() pb = &d; cout << "pb now points to dn"; cout << "Calling pb->print()n"; pb->print(); // uses D::print() return 0; }
31 
Output 
$ g++ -Wall -o virtual virtual.cc $ virtual pb now points to b Calling pb->print() i value is 3 inside object of type B pb now points to d Calling pb->print() i value is 5 inside object of type D $
32 
7.1 Representing Shapes 
shape 
rectangle 
square 
triangle 
circle 
• • • • 
inherits (isa)
33 
C++ Shape Classes 
class shape { public: virtual double area() = 0; }; class rectangle: public shape { public: double area() const {return (height*width);} : private: double height, width; };
34 
class circle: public shape { public: double area() const {return (PI*radius*radius);} : private: double radius; }; // etc
35 
Use: 
shape* p[N]; circle c1,...; rectangle r1,...; : // fill in p with pointers to // circles, squares, etc p[0] = &c1; p[1] = &r1; ... : : // calculate total area for (i = 0; i < N; ++i) tot_area = tot_area + p[i]->area();
36 
Coding shape in C 
enum shapekinds {CIRCLE, RECT, ...}; struct shape { enum shapekinds s_val; double centre, radius, height, ...; : /* data for all shapes must go here */ }; 
continued
37 
double area(shape *s) { switch (s->s_val) { case CIRCLE: return (PI*s->radius*s->radius); case RECT: return (s->height*s->width); : /* area code for all shapes must go here */ } 
add a new kind of shape?
38 
Dynamic Binding Reviewed 
Advantages: 
–Extensions of the inheritance hierarchy leaves the client’s code unaltered. 
–Code is localised – each class is responsible for the meaning of its functions (e.g. print()). 
Disadvantage: 
–(Small) run-time overhead.
39 
8. C++ Pros and Cons 
6.1. Reasons for using C++ 
6.2. Reasons for not using C++
40 
8.1 Reasons for using C++ 
bandwagon effect 
C++ is a superset of C 
–familiarity 
–installed base can be kept 
–can ‘pretend’ to code in C++ 
efficient implementation 
continued
41 
low-level and high-level features 
portable 
a better C 
no need for fancy OOP resources
42 
8.2 Reasons for not using C++ 
a hybrid 
size 
confusing syntax and semantics 
programmers must decide between efficiency and elegance 
no automatic garbage collection

More Related Content

What's hot

Object Oriented Programming - Constructors & Destructors
Object Oriented Programming - Constructors & DestructorsObject Oriented Programming - Constructors & Destructors
Object Oriented Programming - Constructors & Destructors
Dudy Ali
 
Nonlinear 2nd order analysis of 2 d fixed support beam with plastic hinge con...
Nonlinear 2nd order analysis of 2 d fixed support beam with plastic hinge con...Nonlinear 2nd order analysis of 2 d fixed support beam with plastic hinge con...
Nonlinear 2nd order analysis of 2 d fixed support beam with plastic hinge con...
Salar Delavar Qashqai
 
ATS Programming
ATS ProgrammingATS Programming
ATS Programming
Zhiqiang Ren
 
Java cheatsheet
Java cheatsheetJava cheatsheet
Java cheatsheet
Anass SABANI
 
Oop concept in c++ by MUhammed Thanveer Melayi
Oop concept in c++ by MUhammed Thanveer MelayiOop concept in c++ by MUhammed Thanveer Melayi
Oop concept in c++ by MUhammed Thanveer Melayi
Muhammed Thanveer M
 
Gentle Introduction to Functional Programming
Gentle Introduction to Functional ProgrammingGentle Introduction to Functional Programming
Gentle Introduction to Functional Programming
Saurabh Singh
 
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...
ssuserd6b1fd
 
OO-like C Programming: Struct Inheritance and Virtual Function
OO-like C Programming: Struct Inheritance and Virtual FunctionOO-like C Programming: Struct Inheritance and Virtual Function
OO-like C Programming: Struct Inheritance and Virtual Function
Yu-Sheng (Yosen) Chen
 
Pf cs102 programming-10 [structs]
Pf cs102 programming-10 [structs]Pf cs102 programming-10 [structs]
Pf cs102 programming-10 [structs]
Abdullah khawar
 
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...
ssuserd6b1fd
 
Labsheet2 stud
Labsheet2 studLabsheet2 stud
Labsheet2 studrohassanie
 
C Programming Language Part 11
C Programming Language Part 11C Programming Language Part 11
C Programming Language Part 11
Rumman Ansari
 
Chapter 7 functions (c)
Chapter 7 functions (c)Chapter 7 functions (c)
Chapter 7 functions (c)
hhliu
 

What's hot (16)

Object Oriented Programming - Constructors & Destructors
Object Oriented Programming - Constructors & DestructorsObject Oriented Programming - Constructors & Destructors
Object Oriented Programming - Constructors & Destructors
 
Pointers in c
Pointers in cPointers in c
Pointers in c
 
Nonlinear 2nd order analysis of 2 d fixed support beam with plastic hinge con...
Nonlinear 2nd order analysis of 2 d fixed support beam with plastic hinge con...Nonlinear 2nd order analysis of 2 d fixed support beam with plastic hinge con...
Nonlinear 2nd order analysis of 2 d fixed support beam with plastic hinge con...
 
ATS Programming
ATS ProgrammingATS Programming
ATS Programming
 
Java cheatsheet
Java cheatsheetJava cheatsheet
Java cheatsheet
 
Oop concept in c++ by MUhammed Thanveer Melayi
Oop concept in c++ by MUhammed Thanveer MelayiOop concept in c++ by MUhammed Thanveer Melayi
Oop concept in c++ by MUhammed Thanveer Melayi
 
Gentle Introduction to Functional Programming
Gentle Introduction to Functional ProgrammingGentle Introduction to Functional Programming
Gentle Introduction to Functional Programming
 
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...
 
OO-like C Programming: Struct Inheritance and Virtual Function
OO-like C Programming: Struct Inheritance and Virtual FunctionOO-like C Programming: Struct Inheritance and Virtual Function
OO-like C Programming: Struct Inheritance and Virtual Function
 
Pf cs102 programming-10 [structs]
Pf cs102 programming-10 [structs]Pf cs102 programming-10 [structs]
Pf cs102 programming-10 [structs]
 
Lr5
Lr5Lr5
Lr5
 
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...
 
Labsheet2 stud
Labsheet2 studLabsheet2 stud
Labsheet2 stud
 
C Programming Language Part 11
C Programming Language Part 11C Programming Language Part 11
C Programming Language Part 11
 
Chapter 7 functions (c)
Chapter 7 functions (c)Chapter 7 functions (c)
Chapter 7 functions (c)
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 

Similar to L10

02.adt
02.adt02.adt
Example for Abstract Class and Interface.pdf
Example for Abstract Class and Interface.pdfExample for Abstract Class and Interface.pdf
Example for Abstract Class and Interface.pdf
rajaratna4
 
classes & objects.ppt
classes & objects.pptclasses & objects.ppt
classes & objects.ppt
BArulmozhi
 
breaking_dependencies_the_solid_principles__klaus_iglberger__cppcon_2020.pdf
breaking_dependencies_the_solid_principles__klaus_iglberger__cppcon_2020.pdfbreaking_dependencies_the_solid_principles__klaus_iglberger__cppcon_2020.pdf
breaking_dependencies_the_solid_principles__klaus_iglberger__cppcon_2020.pdf
VishalKumarJha10
 
C++ L11-Polymorphism
C++ L11-PolymorphismC++ L11-Polymorphism
C++ L11-Polymorphism
Mohammad Shaker
 
Structure in programming in c or c++ or c# or java
Structure in programming  in c or c++ or c# or javaStructure in programming  in c or c++ or c# or java
Structure in programming in c or c++ or c# or java
Samsil Arefin
 
Structure in c
Structure in cStructure in c
Structure in c
Samsil Arefin
 
Static and const members
Static and const membersStatic and const members
Static and const members
mohamed sikander
 
175035 cse lab-05
175035 cse lab-05 175035 cse lab-05
175035 cse lab-05
Mahbubay Rabbani Mim
 
C++ Language
C++ LanguageC++ Language
C++ Language
Vidyacenter
 
Pads lab manual final
Pads lab manual finalPads lab manual final
Pads lab manual final
AhalyaR
 
Inheritance in C++.ppt
Inheritance in C++.pptInheritance in C++.ppt
Inheritance in C++.ppt
instaface
 
Value Objects, Full Throttle (to be updated for spring TC39 meetings)
Value Objects, Full Throttle (to be updated for spring TC39 meetings)Value Objects, Full Throttle (to be updated for spring TC39 meetings)
Value Objects, Full Throttle (to be updated for spring TC39 meetings)
Brendan Eich
 
Inheritance (1)
Inheritance (1)Inheritance (1)
Inheritance (1)
sanya6900
 
c++-language-1208539706757125-9.pdf
c++-language-1208539706757125-9.pdfc++-language-1208539706757125-9.pdf
c++-language-1208539706757125-9.pdf
nisarmca
 
Object Oriented Programming using C++: Ch11 Virtual Functions.pptx
Object Oriented Programming using C++: Ch11 Virtual Functions.pptxObject Oriented Programming using C++: Ch11 Virtual Functions.pptx
Object Oriented Programming using C++: Ch11 Virtual Functions.pptx
RashidFaridChishti
 
Constructors and Destructors
Constructors and DestructorsConstructors and Destructors
Constructors and Destructors
Keyur Vadodariya
 
Golang and Eco-System Introduction / Overview
Golang and Eco-System Introduction / OverviewGolang and Eco-System Introduction / Overview
Golang and Eco-System Introduction / Overview
Markus Schneider
 

Similar to L10 (20)

02.adt
02.adt02.adt
02.adt
 
Example for Abstract Class and Interface.pdf
Example for Abstract Class and Interface.pdfExample for Abstract Class and Interface.pdf
Example for Abstract Class and Interface.pdf
 
classes & objects.ppt
classes & objects.pptclasses & objects.ppt
classes & objects.ppt
 
breaking_dependencies_the_solid_principles__klaus_iglberger__cppcon_2020.pdf
breaking_dependencies_the_solid_principles__klaus_iglberger__cppcon_2020.pdfbreaking_dependencies_the_solid_principles__klaus_iglberger__cppcon_2020.pdf
breaking_dependencies_the_solid_principles__klaus_iglberger__cppcon_2020.pdf
 
C++ L11-Polymorphism
C++ L11-PolymorphismC++ L11-Polymorphism
C++ L11-Polymorphism
 
Structure in programming in c or c++ or c# or java
Structure in programming  in c or c++ or c# or javaStructure in programming  in c or c++ or c# or java
Structure in programming in c or c++ or c# or java
 
Structure in c
Structure in cStructure in c
Structure in c
 
Static and const members
Static and const membersStatic and const members
Static and const members
 
175035 cse lab-05
175035 cse lab-05 175035 cse lab-05
175035 cse lab-05
 
C++ Language
C++ LanguageC++ Language
C++ Language
 
Pads lab manual final
Pads lab manual finalPads lab manual final
Pads lab manual final
 
Inheritance in C++.ppt
Inheritance in C++.pptInheritance in C++.ppt
Inheritance in C++.ppt
 
Value Objects, Full Throttle (to be updated for spring TC39 meetings)
Value Objects, Full Throttle (to be updated for spring TC39 meetings)Value Objects, Full Throttle (to be updated for spring TC39 meetings)
Value Objects, Full Throttle (to be updated for spring TC39 meetings)
 
Basics of objective c
Basics of objective cBasics of objective c
Basics of objective c
 
Inheritance (1)
Inheritance (1)Inheritance (1)
Inheritance (1)
 
Oops concept
Oops conceptOops concept
Oops concept
 
c++-language-1208539706757125-9.pdf
c++-language-1208539706757125-9.pdfc++-language-1208539706757125-9.pdf
c++-language-1208539706757125-9.pdf
 
Object Oriented Programming using C++: Ch11 Virtual Functions.pptx
Object Oriented Programming using C++: Ch11 Virtual Functions.pptxObject Oriented Programming using C++: Ch11 Virtual Functions.pptx
Object Oriented Programming using C++: Ch11 Virtual Functions.pptx
 
Constructors and Destructors
Constructors and DestructorsConstructors and Destructors
Constructors and Destructors
 
Golang and Eco-System Introduction / Overview
Golang and Eco-System Introduction / OverviewGolang and Eco-System Introduction / Overview
Golang and Eco-System Introduction / Overview
 

More from lksoo

Lo48
Lo48Lo48
Lo48
lksoo
 
Lo43
Lo43Lo43
Lo43
lksoo
 
Lo39
Lo39Lo39
Lo39lksoo
 
Lo37
Lo37Lo37
Lo37
lksoo
 
Lo27
Lo27Lo27
Lo27
lksoo
 
Lo17
Lo17Lo17
Lo17
lksoo
 
Lo12
Lo12Lo12
Lo12
lksoo
 
T3
T3T3
T3
lksoo
 
T2
T2T2
T2
lksoo
 
T1
T1T1
T1
lksoo
 
T4
T4T4
T4
lksoo
 
P5
P5P5
P5
lksoo
 
P4
P4P4
P4
lksoo
 
P3
P3P3
P3
lksoo
 
P1
P1P1
P1
lksoo
 
P2
P2P2
P2
lksoo
 
L9
L9L9
L9
lksoo
 
L8
L8L8
L8
lksoo
 
L7
L7L7
L7
lksoo
 
L6
L6L6
L6
lksoo
 

More from lksoo (20)

Lo48
Lo48Lo48
Lo48
 
Lo43
Lo43Lo43
Lo43
 
Lo39
Lo39Lo39
Lo39
 
Lo37
Lo37Lo37
Lo37
 
Lo27
Lo27Lo27
Lo27
 
Lo17
Lo17Lo17
Lo17
 
Lo12
Lo12Lo12
Lo12
 
T3
T3T3
T3
 
T2
T2T2
T2
 
T1
T1T1
T1
 
T4
T4T4
T4
 
P5
P5P5
P5
 
P4
P4P4
P4
 
P3
P3P3
P3
 
P1
P1P1
P1
 
P2
P2P2
P2
 
L9
L9L9
L9
 
L8
L8L8
L8
 
L7
L7L7
L7
 
L6
L6L6
L6
 

Recently uploaded

Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
EverAndrsGuerraGuerr
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
Jean Carlos Nunes Paixão
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
GeoBlogs
 
The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
DhatriParmar
 
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th SemesterGuidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Atul Kumar Singh
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
MysoreMuleSoftMeetup
 
"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
SACHIN R KONDAGURI
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
Jisc
 
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdfAdversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Po-Chuan Chen
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
Pavel ( NSTU)
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
Thiyagu K
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
TechSoup
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Thiyagu K
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
Levi Shapiro
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
Special education needs
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
Sandy Millin
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
vaibhavrinwa19
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
Delapenabediema
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
siemaillard
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
Ashokrao Mane college of Pharmacy Peth-Vadgaon
 

Recently uploaded (20)

Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
 
The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
 
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th SemesterGuidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th Semester
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
 
"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
 
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdfAdversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
 

L10

  • 1. 1 Inheritance and Polymorphism Andrew Davison Noppadon Kamolvilassatian Department of Computer Engineering Prince of Songkla University
  • 2. 2 Contents 1. Key OOP Features 2. Inheritance Concepts 3. Inheritance Examples 4. Implementing Inheritance in C++ 5. Polymorphism 6. Inclusion (Dynamic Binding) 7. Virtual Function Examples 8. C++ Pros and Cons
  • 3. 3 1. Key OOP Features ADTs (done in the last section) Inheritance Polymorphism
  • 4. 4 2. Inheritance Concepts Derive a new class (subclass) from an existing class (base class or superclass). Inheritance creates a hierarchy of related classes (types) which share code and interface.
  • 5. 5 3. Inheritance Examples Base ClassDerived ClassesStudentCommuterStudentResidentStudentShapeCircleTriangleRectangleLoanCarLoanHomeImprovementLoanMortgageLoan
  • 6. 6 More Examples Base ClassDerived ClassesEmployeeManagerResearcherWorkerAccountCheckingAccountSavingAccount
  • 7. 7 University community members Employee CommunityMember Student Faculty Staff Administrator Teacher
  • 8. 8 Shape class hierarchy TwoDimensionalShape Shape ThreeDimensionalShape Circle Square Triangle Sphere Cube Tetrahedron
  • 9. 9 Credit cards logo american express hologram card owner’s name inherits from (isa) visa card master card pin category
  • 10. 10 4. Implementing Inheritance in C++ Develop a base class called student Use it to define a derived class called grad_student
  • 11. 11 The Student Class Hierarchy student print() year_group() grad_student print() inherits (isa) student_id, year, name dept, thesis
  • 12. 12 Student Class class student { public: student(char* nm, int id, int y); void print(); int year_group() { return year; } private: int student_id; int year; char name[30]; };
  • 13. 13 Member functions student::student(char* nm, int id, int y) { student_id = id; year = y; strcpy(name, nm); } void student::print() { cout << "n" << name << ", " << student_id << ", " << year << endl; }
  • 14. 14 Graduate Student Class class grad_student: public student { public: grad_student(char* nm, int id, int y, char* d, char* th); void print(); private: char dept[10]; char thesis[80]; };
  • 15. 15 Member functions grad_student::grad_student(char* nm, int id, int y, char* d, char* th) :student(nm, id, y) { strcpy(dept, d); strcpy(thesis, th); } void grad_student::print() { student::print(); cout << dept << ", " << thesis << endl; }
  • 16. 16 Use int main() { student s1("Jane Doe", 100, 1); grad_student gs1("John Smith", 200, 4, "Pharmacy", "Retail Thesis"); cout << "Student classes example:n"; cout << "n Student s1:"; s1.print(); cout << “Year “ << s1.year_group() << endl; : continued
  • 17. 17 cout << "n Grad student gs1:"; gs1.print(); cout << “Year “ << gs1.year_group() << endl; :
  • 18. 18 Using Pointers student *ps; grad_student *pgs; ps = &s1; cout << "n ps, pointing to s1:"; ps->print(); ps = &gs1; cout << "n ps, pointing to gs1:"; ps->print(); pgs = &gs1; cout << "n pgs, pointing to gs1:"; pgs->print(); return 0; }
  • 19. 19 Output $ g++ -Wall -o gstudent gstudent.cc $ gstudent Student classes example: Student s1: Jane Doe, 100, 1 Year 1 Grad student gs1: John Smith, 200, 4 Pharmacy, Retail Thesis Year 4 : continued
  • 20. 20 ps, pointing to s1: Jane Doe, 100, 1 ps, pointing to gs1: John Smith, 200, 4 pgs, pointing to gs1: John Smith, 200, 4 Pharmacy, Retail Thesis $ student print() used. grad_student print() used.
  • 21. 21 Notes The choice of print() depends on the pointer type, not the object pointed to. This is a compile time decision (called static binding).
  • 22. 22 5. Polymorphism Webster: "Capable of assuming various forms." Four main kinds: 1. coercion a / b 2. overloading a + b continued
  • 23. 23 3. inclusion (dynamic binding) –Dynamic binding of a function call to a function. 4. parametric –The type argument is left unspecified and is later instantiated e.g generics, templates
  • 24. 24 6. Inclusion (dynamic binding) 5.1. Dynamic Binding in OOP 5.2. Virtual Function Example 5.3. Representing Shapes 5.4. Dynamic Binding Reviewed
  • 25. 25 Dynamic Binding in OOP X print() Classes Y print() Z print() inherits (isa) X x; Y y; Z z; X *px; px = & ??; // can be x,y,or z px->print(); // ??
  • 26. 26 Two Types of Binding Static Binding (the default in C++) –px->print() uses X’s print –this is known at compile time Dynamic Binding –px->print() uses the print() in the object pointed at –this is only known at run time –coded in C++ with virtual functions
  • 27. 27 Why “only known at run time”? Assume dynamic binding is being used: X x; Y y; Z z; X *px; : cin >> val; if (val == 1) px = &x; else px = &y; px->print(); // which print() is used?
  • 28. 28 7. Virtual Function Examples class B { public: int i; virtual void print() { cout << "i value is " << i << " inside object of type Bnn"; } }; class D: public B { public: void print() { cout << "i value is " << i << " inside object of type Dnn"; } };
  • 29. 29 Use int main() { B b; B *pb; D d; // initilise i values in objects b.i = 3; d.i = 5; :
  • 30. 30 pb = &b; cout << "pb now points to bn"; cout << "Calling pb->print()n"; pb->print(); // uses B::print() pb = &d; cout << "pb now points to dn"; cout << "Calling pb->print()n"; pb->print(); // uses D::print() return 0; }
  • 31. 31 Output $ g++ -Wall -o virtual virtual.cc $ virtual pb now points to b Calling pb->print() i value is 3 inside object of type B pb now points to d Calling pb->print() i value is 5 inside object of type D $
  • 32. 32 7.1 Representing Shapes shape rectangle square triangle circle • • • • inherits (isa)
  • 33. 33 C++ Shape Classes class shape { public: virtual double area() = 0; }; class rectangle: public shape { public: double area() const {return (height*width);} : private: double height, width; };
  • 34. 34 class circle: public shape { public: double area() const {return (PI*radius*radius);} : private: double radius; }; // etc
  • 35. 35 Use: shape* p[N]; circle c1,...; rectangle r1,...; : // fill in p with pointers to // circles, squares, etc p[0] = &c1; p[1] = &r1; ... : : // calculate total area for (i = 0; i < N; ++i) tot_area = tot_area + p[i]->area();
  • 36. 36 Coding shape in C enum shapekinds {CIRCLE, RECT, ...}; struct shape { enum shapekinds s_val; double centre, radius, height, ...; : /* data for all shapes must go here */ }; continued
  • 37. 37 double area(shape *s) { switch (s->s_val) { case CIRCLE: return (PI*s->radius*s->radius); case RECT: return (s->height*s->width); : /* area code for all shapes must go here */ } add a new kind of shape?
  • 38. 38 Dynamic Binding Reviewed Advantages: –Extensions of the inheritance hierarchy leaves the client’s code unaltered. –Code is localised – each class is responsible for the meaning of its functions (e.g. print()). Disadvantage: –(Small) run-time overhead.
  • 39. 39 8. C++ Pros and Cons 6.1. Reasons for using C++ 6.2. Reasons for not using C++
  • 40. 40 8.1 Reasons for using C++ bandwagon effect C++ is a superset of C –familiarity –installed base can be kept –can ‘pretend’ to code in C++ efficient implementation continued
  • 41. 41 low-level and high-level features portable a better C no need for fancy OOP resources
  • 42. 42 8.2 Reasons for not using C++ a hybrid size confusing syntax and semantics programmers must decide between efficiency and elegance no automatic garbage collection