1 Inheritance and Polymorphism Andrew Davison Noppadon Kamolvilassatian Department of Computer Engineering Prince of Songkla University.

Slides:



Advertisements
Similar presentations
The C ++ Language BY Shery khan. The C++ Language Bjarne Stroupstrup, the language’s creator C++ was designed to provide Simula’s facilities for program.
Advertisements

Department of Computer Engineering Faculty of Engineering, Prince of Songkla University 1 5 – Abstract Data Types.
C12, Polymorphism “many forms” (greek: poly = many, morphos = form)
Inheritance. Today: Inheritance and derived classes Is-A relationship class hierarchies proper inheritance (pure) polymorphism virtual functions protected.
1 Inheritance Concepts n Derive a new class (subclass) from an existing class (base class or superclass). n Inheritance creates a hierarchy of related.
1 CS 201 Introduction to c++ (2) Debzani Deb. 2 Classes (1) A class definition – in a header file :.h file A class implementation – in a.cc,.cpp file.
12/08/08MET CS Fall Polymorphism 10. Polymorphism Goal: Goal: Create methods that can be invoked with all object types, base as well as.
Inheritance and Polymorphism CS351 – Programming Paradigms.
Virtual Functions Junaed Sattar November 10, 2008 Lecture 10.
Lecture 6: Polymorphism - The fourth pillar of OOP - 1.
Engr 691 Special Topics in Engineering Science Software Architecture Spring Semester 2004 Lecture Notes.
Programming Languages and Paradigms Object-Oriented Programming.
1 Data Structures - CSCI 102 CS102 C++ Polymorphism Prof Tejada.
CSE 425: Object-Oriented Programming II Implementation of OO Languages Efficient use of instructions and program storage –E.g., a C++ object is stored.
Polymorphism &Virtual Functions
Lecture 3 Casting Abstract Classes and Methods Interfaces.
CSE 332: C++ templates This Week C++ Templates –Another form of polymorphism (interface based) –Let you plug different types into reusable code Assigned.
1 Introduction to C++ Noppadon Kamolvilassatian Department of Computer Engineering Prince of Songkla University.
Programming Fundamentals 2: Inheritance/ F II Objectives – –the use of super, overriding, method polymorphism (dynamic binding), protected.
 2002 Prentice Hall. All rights reserved. 1 Introduction to Inheritance Inheritance: –1 of 3 main features of OOP –Form of software reusability –(Derived)
Objective-C1 CS151 Presentation: Objective C Kai Tai Pang William Sze.
Chris Kiekintveld CS 2401 (Fall 2010) Elementary Data Structures and Algorithms Inheritance and Polymorphism.
Week 14 - Monday.  What did we talk about last time?  Introduction to C++  Input and output  Functions  Overloadable  Default parameters  Pass.
Outline §Review of the last class l class variables and methods l method overloading and overriding §Inheritance and polymorphism l polymorphism l abstract.
CSC241 Object-Oriented Programming (OOP) Lecture No. 16.
LECTURE LECTURE 15 Inheritance Text book p
Chapter 10 Inheritance and Polymorphism
Fundamentals of C++ Yingcai Xiao 09/03/08. Outline Class Definition IO Template vector C Pointer Dynamic Memory Allocation.
1 Lecture 6: Polymorphism - The fourth pillar of OOP -
Lecture 10 Concepts of Programming Languages Arne Kutzner Hanyang University / Seoul Korea.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Object-Oriented Programming Chapter Chapter
Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives  Inheritance  Virtual Function.
Object Oriented Programming
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
Chapter -6 Polymorphism
Inheritance Initialization & Destruction of Derived Objects Protected Members Non-public Inheritance Virtual Function Implementation Virtual Destructors.
1 Introduction to C++ Noppadon Kamolvilassatian Department of Computer Engineering Prince of Songkla University.
Variations on Inheritance Object-Oriented Programming Spring
Copyright 2005, The Ohio State University CSE – Introduction to C++ Name: Shirish Tatikonda Time: T 3:30 PM Room: BE 394
Object Oriented Programming in C++ Chapter 7 Dynamic Binding.
Polymorphism and Virtual Functions One name many shapes behaviour Unit - 07.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 20 - Virtual Functions Outline 20.1Introduction 20.2Type Fields and switch Statements 20.3Virtual.
Copyright © 2012 Pearson Education, Inc. Chapter 10 Advanced Topics.
CSC241 Object-Oriented Programming (OOP) Lecture No. 17.
Inheritance - 3. Virtual Functions Functions defined as virtual are ones that the base expects its derived classes may redefine. Functions defined as.
Computer Science Department Inheritance & Polymorphism.
1 Inheritance and Polymorphism Chapter Getting Started Continue the Cat Management example from previous presentation.
CPSC 252Inheritance II Page 1 Inheritance & Pointers Consider the following client code: const int MAXCLOCKS = 2; Clock* clockPtr[ MAXCLOCKS ]; clockPtr[0]
ISBN Chapter 12 Support for Object-Oriented Programming.
C++ Programming Lecture 13 Functions – Part V By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
Abstract classes only used as base class from which other classes can be inherit cannot be used to instantiate any objects are incomplete Classes that.
DEVRY COMP 220 iLab 7 Polymorphism Lab Report and Source Code Check this A+ tutorial guideline at
Friends of Template Classes
Advanced Program Design with C++
Polymorphism.
Inheritance and Run time Polymorphism
Object-Oriented Programming (OOP) Lecture No. 28
Learning Objectives Inheritance Virtual Function.
Classes in C++ C++ originally called "C with classes":
Inheritance and Polymorphism
Inheritance Virtual Functions, Dynamic Binding, and Polymorphism
Programming II Polymorphism A.AlOsaimi.
F II 8. More on Inheritance Objectives
C++ Programming CLASS This pointer Static Class Friend Class
Lecture 10 Concepts of Programming Languages
CS410 – Software Engineering Lecture #8: Advanced C++ III
Lecture 6: Polymorphism
Static Binding Static binding chooses the function in the class of the base class pointer, ignoring any versions in the class of the object actually.
Computer Science II for Majors
Presentation transcript:

1 Inheritance and Polymorphism Andrew Davison Noppadon Kamolvilassatian Department of Computer Engineering Prince of Songkla University

2 Contents n 1. Key OOP Features n 2. Inheritance Concepts n 3. Inheritance Examples n 4. Implementing Inheritance in C++ n 5. Polymorphism n 6. Inclusion (Dynamic Binding) n 7. Virtual Function Examples n 8. C++ Pros and Cons

3 1. Key OOP Features n ADTs (done in the last section) n Inheritance n Polymorphism

4 2. Inheritance Concepts n Derive a new class (subclass) from an existing class (base class or superclass). n Inheritance creates a hierarchy of related classes (types) which share code and interface.

5 3. Inheritance Examples

6 More Examples

7 University community members Employee CommunityMember Student FacultyStaff AdministratorTeacher

8 Shape class hierarchy TwoDimensionalShape Shape ThreeDimensionalShape CircleSquareTriangleSphereCubeTetrahedron

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 print(); ps = &gs1; cout print(); pgs = &gs1; cout 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. n 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 inherits (isa) X x; Y y; Z z; X *px; px = & ??; // can be x,y,or z px->print(); // ??

26 Two Types of Binding n Static Binding (the default in C++) –px->print() uses X ’s print –this is known at compile time n 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 B\n\n"; } }; class D: public B { public: void print() { cout << "i value is " << i << " inside object of type D\n\n"; } };

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 print()\n"; pb->print(); // uses B::print() pb = &d; cout 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 $

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 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 */ } n add a new kind of shape?

38 Dynamic Binding Reviewed n 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() ). n Disadvantage: –(Small) run-time overhead.

39 8. C++ Pros and Cons 6.1. Reasons for using C Reasons for not using C++

Reasons for using C++ n bandwagon effect n C++ is a superset of C –familiarity –installed base can be kept –can ‘pretend’ to code in C++ n efficient implementation continued

41 n low-level and high-level features n portable n a better C n no need for fancy OOP resources

Reasons for not using C++ n a hybrid n size n confusing syntax and semantics n programmers must decide between efficiency and elegance n no automatic garbage collection