C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved.

Similar documents
Cpt S 122 Data Structures. Inheritance

Inheritance (Deitel chapter 9)

Programming in C# Inheritance and Polymorphism

Object Oriented Programming. CISC181 Introduction to Computer Science. Dr. McCoy. Lecture 27 December 8, What is a class? Extending a Hierarchy

INHERITANCE - Part 1. CSC 330 OO Software Design 1

A A B U n i v e r s i t y

Objectives. INHERITANCE - Part 1. Using inheritance to promote software reusability. OOP Major Capabilities. When using Inheritance?

Inheritance Motivation

INHERITANCE - Part 1. CSC 330 OO Software Design 1

Chapter 9 - Object-Oriented Programming: Inheritance

Problem: Given a vector of pointers to Shape objects, print the area of each of the shape.

C++ 프로그래밍실습. Visual Studio Smart Computing Laboratory

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Chapter 19 - C++ Inheritance

Chapter 19 C++ Inheritance

Fig. 9.1 Fig. 9.2 Fig. 9.3 Fig. 9.4 Fig. 9.5 Fig. 9.6 Fig. 9.7 Fig. 9.8 Fig. 9.9 Fig Fig. 9.11

Introduction to inheritance

CHAPTER 6 Class-Advanced Concepts - Inheritance

BBM 102 Introduction to Programming II Spring Inheritance

CS111: PROGRAMMING LANGUAGE II

Inheritance Introduction. 9.1 Introduction 361

IS 0020 Program Design and Software Tools

Inheritance, and Polymorphism.

Object Oriented Programming

C++ Programming: Inheritance

Class (Inheritance) SSE2034: System Software Experiment 3, Fall 2018, Jinkyu Jeong

Computer Programming Inheritance 10 th Lecture

Data Structures (INE2011)

Chapter 1: Object-Oriented Programming Using C++

Polymorphism Part 1 1

Object Oriented Design Final Exam (From 3:30 pm to 4:45 pm) Name:

More C++ : Vectors, Classes, Inheritance, Templates

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe

More C++ : Vectors, Classes, Inheritance, Templates. with content from cplusplus.com, codeguru.com

CREATED BY: Muhammad Bilal Arslan Ahmad Shaad. JAVA Chapter No 5. Instructor: Muhammad Naveed

Module 7 b. -Namespaces -Exceptions handling

CSCI-1200 Computer Science II Fall 2006 Lecture 23 C++ Inheritance and Polymorphism

ECE 3574: Dynamic Polymorphism using Inheritance

Extending Classes (contd.) (Chapter 15) Questions:

Java Object Oriented Design. CSC207 Fall 2014

Lecture 5: Inheritance

Where do we stand on inheritance?

OBJECT ORIENTED PROGRAMMING USING C++

CMSC 202 Section 010x Spring Justin Martineau, Tuesday 11:30am

Object Oriented Design

Chapter 20 - C++ Virtual Functions and Polymorphism

Friend Functions, Inheritance

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat Chapter 6 Inheritance Extending a Class

C++ Memory Map. A pointer is a variable that holds a memory address, usually the location of another variable in memory.

Distributed Real-Time Control Systems. Lecture 14 Intro to C++ Part III

2 nd Week Lecture Notes

Data type of a pointer must be same as the data type of the variable to which the pointer variable is pointing. Here are a few examples:

a. a * c - 10 = b. a % b + (a * d) + 7 =

Polymorphism. Arizona State University 1

Jayaram college of Engineering and Technology, Pagalavadi. CS2203 Object Oriented Programming Question Bank Prepared By: S.Gopalakrishnan, Lecturer/IT

What is Polymorphism? Quotes from Deitel & Deitel s. Why polymorphism? How? How? Polymorphism Part 1

Increases Program Structure which results in greater reliability. Polymorphism

Introduction Of Classes ( OOPS )

IUE Faculty of Engineering and Computer Sciences Spring Semester

Inheritance (continued) Inheritance

Object Oriented Programming. Assistant Lecture Omar Al Khayat 2 nd Year

CSC330 Object Oriented Programming. Inheritance

2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program

UNIVERSITI TEKNIKAL MALAYSIA MELAKA FACULTY INFORMATION TECHNOLOGY AND COMMUNICATION (FTMK) BITE 1513 GAME PROGRAMMING I.

Chapter 9 Objects and Classes. Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.

The mechanism that allows us to extend the definition of a class without making any physical changes to the existing class is called inheritance.

CS250 Intro to CS II. Spring CS250 - Intro to CS II 1

Distributed Real-Time Control Systems. Chapter 13 C++ Class Hierarchies

CS 162, Lecture 25: Exam II Review. 30 May 2018

INHERITANCE PART 2. Constructors and Destructors under. Multiple Inheritance. Common Programming Errors. CSC 330 OO Software Design 1

SSE2034: System Software Experiment 3 Spring 2016

Comp151. Inheritance: Initialization & Substitution Principle

AN OVERVIEW OF C++ 1

CSC1322 Object-Oriented Programming Concepts

COEN244: Polymorphism

Inheritance. Software Engineering with Inheritance. CSC330 Object Oriented Programming. Base Classes and Derived Classes. Class Relationships I

Chapter 11 Inheritance and Polymorphism. Motivations. Suppose you will define classes to model circles,

Tokens, Expressions and Control Structures

ITI Introduction to Computing II

OOP. Unit:3.3 Inheritance

Lesson Plan. Subject: OBJECT ORIENTED PROGRAMMING USING C++ :15 weeks (From January, 2018 to April,2018)

ITI Introduction to Computing II

CSE 143. "Class Relationships" Class Relationships and Inheritance. A Different Relationship. Has-a vs. Is-a. Hierarchies of Organization

The Notion of a Class and Some Other Key Ideas (contd.) Questions:

Inheritance and Overloading. Week 11

Polymorphism CSCI 201 Principles of Software Development

Object Orientated Analysis and Design. Benjamin Kenwright

Review Questions for Final Exam

Object Oriented Software Design II

Syllabus for Bachelor of Technology. Computer Engineering. Subject Code: 01CE1303. B.Tech. Year - II

COMPUTER PROGRAMMING (ECE 431) TUTORIAL 9

CMSC 202 Midterm Exam 1 Fall 2015

Object Oriented Software Design II

22. Inheritance. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

Namespaces and Class Hierarchies

Computer Science II (20073) Week 1: Review and Inheritance

Previously, on Lesson Night... From Intermediate Programming, Part 1

Lecture 6. Inheritance

Abstract Data Types (ADT) and C++ Classes

Object Oriented Programming COP3330 / CGS5409

Transcription:

C How to Program, 6/e 1992-2010 by Pearson Education, Inc. All Rights Reserved. 1

Inheritance is a form of software reuse in which you create a class that absorbs an existing class s data and behaviors and enhances them with new capabilities. You can designate that the new class should inherit the members of an existing class. This existing class is called the base class, and the new class is referred to as the derived class. A derived class represents a more specialized group of objects. A derived class contains behaviors inherited from its base class and can contain additional behaviors. A derived class can also customize behaviors inherited from the base class. 1992-2010 by Pearson Education, Inc. All Rights Reserved. 2

Base class Student Shape Loan Employee Account Derived classes GraduateStudent UndergraduateStudent Circle Triangle Rectangle CarLoan HomeImprovementLoan MortgageLoan FacultyMember StaffMember CheckingAccount SavingsAccount 3

A GraduadeStudent is a Student An UndergraduateStudent is also a Student GraduadeStudent is a specialization of Student OR Student is a generalization of GraduadeStudent Base class Student Derived classes GraduateStudent UndergraduateStudent 4

A direct base class is the base class from which a derived class explicitly inherits. An indirect base class is inherited from two or more levels up in the class hierarchy. In the case of single inheritance, a class is derived from one base class. C++ also supports multiple inheritance, in which a derived class inherits from multiple (possibly unrelated) base classes. 1992-2010 by Pearson Education, Inc. All Rights Reserved. 5

With object-oriented programming, you focus on the commonalities among objects in the system rather than on the special cases. We distinguish between the is-a relationship and the has-a relationship. The is-a relationship represents inheritance. In an is-a relationship, an object of a derived class also can be treated as an object of its base class. By contrast, the has-a relationship represents composition. 1992-2010 by Pearson Education, Inc. All Rights Reserved. 6

How to derive a class from an existing one? class derivedclassname : access baseclassname { } access can be public, protected, or private, or it can be omitted (defaults to private) // Base Class class Base { // data members and methods of class Base... // Derived Class class Derived : public Base { // data members and methods of class Derived... Derived class is derived from Base class publicly. 7

// Base Class class Base {... // Derived Class class Derived : public Base {... main() { Base b; Derived c; b = c; // Allowed. c IS-A b. Base *ptr = new Derived(); // Allowed.... } 8

With public inheritance, every object of a derived class is also an object of that derived class s base class. However, base-class objects are not objects of their derived classes. main() { Base b; Derived c; b = c; // Allowed. c IS-A b. c = b; // WRONG. b IS NOT c.... } 9

Point (x,y) radius Circle height Cylinder 10

Circle x,y and radius Point x, y 3D-Point x, y and z class Point { protected: int x, y; public: void set(int a, int b); } class Circle : public Point { private: double radius; } class 3D-Point: public Point { private: int z; } 11

Circle Point x, y class Point { protected: int x, y; public: void set(int a, int b); } class Circle : public Point { private: } x,y and radius double radius; class Circle { protected: int x,y; private: double radius; public: void set(int a, int b); } 12

C++ class Point { public: int x, y; class Circle : public Point { double radius; Equivalent C implementation struct Point { int x, y struct Circle { int x, y; double radius; 13

Inheritance augment + specialize Augmenting the original class Point Circle 3D-Point Specializing the original class ComplexNumber real imag real RealNumber ImaginaryNumber imag 14

derive from members go to base class/superclass / parent class Two levels of access control over class members class definition inheritance type derived class/subclass / child class class Point { protected: int x, y; public: void set(int a,int b); class Circle : public Point { 15

Derived-class member functions might require access to base class data members and member functions. A derived class can access the non-private members of its base class. Base class members that should not be accessible to the member functions of derived classes should be declared private in the base class. A derived class can change the values of private base-class members, but only through non-private member functions provided in the base class and inherited into the derived class. 1992-2010 by Pearson Education, Inc. All Rights Reserved. 16

class Base { /* */ class Derived_1 : public Base { // data members and methods of class Derived_1 class Derived_2 : Base { // data members and methods of class Derived_2 The keyword public in the declaration of Derived_1 shows that derivation is public. Public members of Base is public to Derived_1. (all public members are public, protected members are protected and private members are invisible!!) If no keyword (public, private or protected) is used as in Derived_1, then inheritance is private 17

The base class may be inherited through public, protected or private inheritance. Use of protected and private inheritance is rare, and each should be used only with great care; public inheritance is common. A base class s private members are never accessible directly from a derived class, but can be accessed through calls to the public and protected methods of the base class. Figure 20.27 summarizes for each type of inheritance the accessibility of base-class members in a derived class. 1992-2010 by Pearson Education, Inc. All Rights Reserved. 18

public, protected and private Inheritance 1992-2010 by Pearson Education, Inc. All Rights Reserved. 19

public and private Inheritance When base class inherited as public: class Circle : public Point { } public in base class public in derived class private in base class Inaccessible in derived class When base class inherited as private class Circle : private Point { } public in base class private in derived class private in base class Inaccessible in derived class 20

class Base { public: int x; private: int y: class Derived_1 : public Base { // Can you access x here? // Can you access y here? class Derived_2 : Base { // Can you access x here? // Can you access y here? 21

Every derived class object is an object of its base class, and one base class can have many derived classes. So, the set of objects represented by a base class typically is larger than the set of objects represented by any of its derived classes (See next slide). A base class exists in a hierarchical relationship with its derived classes. A class becomes either a base class supplying members to other classes, a derived class inheriting its members from other classes, or both. 1992-2010 by Pearson Education, Inc. All Rights Reserved. 22

class Base { // Base Class... class Derived_1 : public Base { // Derived Class 1... class Derived_2 : public Base { // Derived Class 2... class Derived_3 : public Derived_1 {... main() { Base b; Derived_1 c1; Derived_2 c2 b = c1; b = c2; // b can be both Derived_1 or Derived_2 } 23

Case Study: Point, Circle, Cylinder A Point can be specified by its position (coordinates). A Circle can be specified by its position and a radius. A Cylinder can be specified by a Circle (position, radius) and height. Point (x,y) radius Circle height Cylinder 24

class Circle { public: Circle(); void setrad(double r); double getrad(); double Diameter(); double Circumference(); private: double radius; class Cylinder : public Circle{ public: double Volume(); void setheigth(double h); private: double height; Base class Circle - radius + setradius() + getradius() + Diameter() + Circumference() Cylinder -height +Volume() +setheigth() Derived class 25

class Circle { public: Circle(); void setrad(double r); double getrad(); double Diameter(); double Circumference(); private: double radius; class Cylinder:public Circle { public: double Volume(); void setheigth(double h); private: double height; MEMBERS FOR CYLINDER Member double radius Access Status in Cylinder Not accessible How Obtained from Circle setrad() public from Circle getrad() public from Circle Diameter() public from Circle Circumference() public from Circle double height setheigth() Volume() private public public its own member its own member its own member 26

#include <iostream> using namespace std; #define PI 3.14 class Circle { public: void setrad(double r){ radius = r; } double getrad() { return radius;} double Diameter() { return radius * 2;} double Circumference() { return 2*PI*radius;} double Area() {return PI * radius * radius;} private: double radius; int main() { Cylinder x; x.setrad(5); x.setheight(2); cout << x.getrad(); cout << endl; cout << x.volume(); } class Cylinder : public Circle { public: double Volume() { return PI*getRad()*getRad()*height; } // Can NOT access to radius use getrad() void setheight(double h) { height = h; } private: double height; 27

class BC { protected: int x; int y; public: int z; class DC: private BC { protected: using BC::x; public: void output() { cout << x; } using BC::z; } void main() { DC dc; cout << dc.z; } Access to an inherited member maybe adusted to that of the base class by declaring it public or protected in the derived class. 28

#define PI 3.14 class Circle { public: void setrad(double r){ radius = r; } double getrad(){ return radius; } double Area() { return radius * radius * PI;} private: X double radius; class Cylinder : public Circle { public: double Volume() { return PI * getrad() * getrad()* height; } double Area() { return 2 * PI * getrad() * height + 2 * PI * getrad() * getrad(); } // 2.pi.r.h + 2.pi.r.r void setheight(double h) { height = h; } private: double height; int main() { Cylinder x; x.setrad(5); x.setheight(2); cout << x.area(); cout << endl; cout << x.volume(); } If a derived class has a member with the same name as a member in base class, local member hides the inherited member 29

When a derived-class member function redefines a baseclass member function, the base-class member can be accessed from the derived class by preceding the base-class member name with the base-class name and the binary scope resolution operator (::). class Circle { public: double Area() { return radius * radius* PI;}... class Cylinder : public Circle { public: double Area() { return 2 * PI* getrad() * height + 2 * Circle::Area(); }... 30

Let s develop a simple inheritance hierarchy with five levels (represented by the UML class diagram in Fig. 20.2). A university community has thousands of members. Employees are either faculty members or staff members. Faculty members are either administrators (such as deans and department chairpersons) or teachers. Some administrators, however, also teach classes. Note that we ve used multiple inheritance to form class AdministratorTeacher. Also, this inheritance hierarchy could contain many other classes. 1992-2010 by Pearson Education, Inc. All Rights Reserved. 31

1992-2010 by Pearson Education, Inc. All Rights Reserved. 32

Each arrow in the hierarchy (Fig. 20.2) represents an is-a relationship. As we follow the arrows in this class hierarchy, we can state an Employee is a CommunityMember and a Teacher is a Faculty member. CommunityMember is the direct base class of Employee, Student and Alumnus. CommunityMember is an indirect base class of all the other classes in the diagram. Starting from the bottom of the diagram, you can follow the arrows and apply the is-a relationship to the topmost base class. An AdministratorTeacher is an Administrator, is a Faculty member, is an Employee and is a CommunityMember. 1992-2010 by Pearson Education, Inc. All Rights Reserved. 33

Consider the Shape inheritance hierarchy in Fig. 20.3. Begins with base class Shape. Classes TwoDimensionalShape and ThreeDimensionalShape derive from base class Shape Shapes are either TwoDimensionalShapes or Three-DimensionalShapes. The third level of this hierarchy contains some more specific types of TwoDimensionalShapes and ThreeDimensionalShapes. As in Fig. 20.2, we can follow the arrows from the bottom of the diagram to the topmost base class in this class hierarchy to identify several is-a relationships. 1992-2010 by Pearson Education, Inc. All Rights Reserved. 34

35

A base class s public members are accessible within its body and anywhere that the program has a handle (i.e., a name, reference or pointer) to an object of that class or one of its derived classes. A base class s private members are accessible only within its body and to the friends of that base class. In this section, we introduce the access specifier protected. Using protected access offers an intermediate level of protection between public and private access. A base class s protected members can be accessed within the body of that base class, by members and friends of that base class, and by members and friends of any classes derived from that base class. Derived-class member functions can refer to public and protected members of the base class simply by using the member names. 1992-2010 by Pearson Education, Inc. All Rights Reserved. 36

In the absence of inheritance protected members are just like private members In public inheritance, a protected member can be accessed ( is visible) as a protected member by the derived class class BC { public : void init_x(); protected: int get_x(); private : int x; void print_x(); class DC : public BC { public: void g() { init_x(); // POSSIBLE get_x(); // POSSIBLE cout << x; // IMPOSSIBLE print_x(); // IMPOSSIBLE } 37

public, protected and private Inheritance When base class inherited as public: class Circle : public Point { } public in base class public in derived class protected in base class protected in derived class When base class inherited as protected: class Circle : protected Point { } public in base class protected in derived class protected in base class protected in derived class When base class inherited as private class Circle : private Point { } public in base class private in derived class protected in base class private in derived class 38

class Animal { public: string species; float lifeexpectancy; bool warmblooded; class Cat : public Animal { public : string range[100]; float favoriteprey[100][100]; class HouseCat: public Cat { public: string toys [10000]; string catdentist; string catdoctor; HouseCat has totally 8 members; 3 of them is its own member 2 of them are directly inherited from Cat; 3 of them are inherited indirectly from Animal 39

When we use inheritance to create a new class from an existing one, the new class inherits the data members and member functions of the existing class. We can customize the new class to meet our needs by including additional members and by redefining base-class members. The derived-class programmer does this in C++ without accessing the base class s source code. The derived class must be able to link to the base class s object code. 1992-2010 by Pearson Education, Inc. All Rights Reserved. 40

ISVs can develop proprietary classes for sale or license and make these classes available to users in object-code format. Users can derive new classes from these library classes rapidly and without accessing the ISVs proprietary source code. All the ISVs need to supply with the object code are the header files. The availability of substantial and useful class libraries delivers the maxi-mum benefits of software reuse through inheritance. 1992-2010 by Pearson Education, Inc. All Rights Reserved. 41

END OF WEEK 4 1992-2010 by Pearson Education, Inc. All Rights Reserved.