SMIE-121 Software Design II School of Mobile Information Engineering, Sun Yat-sen University Lecture.

Slides:



Advertisements
Similar presentations
Chapter 19 - Inheritance Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering National Chung-Cheng University.
Advertisements

Chapter 20- Virtual Functions and Polymorphism Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering National Chung-Cheng.
Shape.h Shape Point Circle Cylinder // SHAPE.H
Esempi Ereditarietà1 // Definition of class Point #ifndef POINT_H #define POINT_H #include using std::ostream; class Point { friend ostream &operator
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 9 - Object-Oriented Programming: Inheritance Outline 9.1 Introduction 9.2 Base Classes and Derived.
UML Class and Sequence Diagrams Violet Slides adapted from Marty Stepp, CSE 403, Winter 2012 CSE 403 Spring 2012 Anton Osobov.
主要内容  LR(0) 分析. 0 S→  E # E→  E+T E→  T T→  id T→  ( E ) 1 S→E  # E→E  +T 5 T→id  3 E→E+  T T→  id T→  (E) 4 E→E+T  9 E→T  6 T→(  E) E→
地理信息系统概述. 数据和信息 (Data & Information) 数据 原始事实 如:员工姓名, 数据可以有数值、图形、声音、视觉数据等 信息 以一定规则组织在一起的事实的集合。
吉林大学远程教育课件 主讲人 : 杨凤杰学 时: 64 ( 第六十二讲 ) 离散数学. 最后,我们构造能识别 A 的 Kleene 闭包 A* 的自动机 M A* =(S A* , I , f A* , s A* , F A* ) , 令 S A* 包括所有的 S A 的状态以及一个 附加的状态 s.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 20- Virtual Functions and Polymorphism Outline 20.1Introduction 20.2Type Fields and switch Statements.
第二部分 行政法律关系主体 第一节 行政主体 一、行政主体 (一)行政主体的概念 cc (二)行政主体资格含义及构成要件 CASE1CASE1\CASE2CASE2 (三)行政主体的职权和职责 1 、行政职权的概念及内容 2 、行政职权的特点 3 、行政职责.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 19 - Inheritance Outline 19.1Introduction 19.2Inheritance: Base Classes and Derived Classes 19.3Protected.
线性代数习题课 吉林大学 术洪亮 第一讲 行 列 式 前面我们已经学习了关 于行列式的概念和一些基本 理论,其主要内容可概括为:
第 4 章 过程与变量的作用范围. 4.1 Visual Basic 的代码模块 Visual Basic 的应用程序是由过程组成的, 过程代码存放在模块中。 Visual Basic 提供了 三类模块,它们是窗体模块、标准模块和类 模块。 窗体模块 窗体模块是大多数 Visual Basic.
1 Review (Week7)_ Classes Part II Outline Composition: Objects as Members of Classes Dynamic Memory static Class Members Operator Overloading.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 9 - Inheritance Outline 9.1Introduction 9.2Inheritance: Base Classes and Derived Classes 9.3.
1 Lecture Note 9_Polymorphism Outline Relationships Among Objects in an Inheritance Hierarchy Invoking Base-Class Functions from Derived-Class object Virtual.
第 3 章 控制流分析 内容概述 – 定义一个函数式编程语言,变量可以指称函数 – 以 dynamic dispatch problem 为例(作为参数的 函数被调用时,究竟执行的是哪个函数) – 规范该控制流分析问题,定义什么是可接受的控 制流分析 – 定义可接受分析在语义模型上的可靠性 – 讨论分析算法.
吉林大学远程教育课件 主讲人 : 杨凤杰学 时: 64 ( 第五十三讲 ) 离散数学. 定义 设 G= ( V , T , S , P ) 是一个语法结构,由 G 产生的语言 (或者说 G 的语言)是由初始状态 S 演绎出来的所有终止符的集合, 记为 L ( G ) ={w  T *
编译原理总结. 基本概念  编译器 、解释器  编译过程 、各过程的功能  编译器在程序执行过程中的作用  编译器的实现途径.
程序设计是计算机学科的核心和灵魂程序设计是计算机学科的核心和灵魂 程序设计基础 第十一章 面向对象软件构造.
 符号表  标识符的作用: 声明部分:定义了各种对象及对应的属性和 使用规则。 程序体:对所定义的对象进行各种操作。 $ididname IdnameAttributeIR  必要性 Token : 新表-符号表(种类、类型等信息):
1 第 7 章 存储过程、触发器和程序包 在很多时候,都需要保存 PL/SQL 程序块,以便 随后可以重新使用。这也意味着,程序块需要一个名 称,这样需才可以调用或者引用它。命名的 PL/SQL 程序块可被独立编译并存储在数据库中,任何与数据 库相连接的应用程序都可以访问这些存储的 PL/SQL 程序块。
1 CSE 403 Design and UML Class Diagrams Reading: UML Distilled Ch. 3, by M. Fowler These lecture slides are copyright (C) Marty Stepp, They may not.
1 TCSS 360, Spring 2005 Lecture Notes Design Phase and UML Class Diagrams Relevant Reading: UML Distilled, Third Edition M. Fowler.
UML January 24, 2011 CSE 403, Winter 2011, Brun Design and UML Class Diagrams.
SMIE-121 Software Design II School of Mobile Information Engineering, Sun Yat-sen University Lecture.
CS342 Data Structure Review of C++: Overriding base- class functions.
《 UML 分析与设计》 交互概述图 授课人:唐一韬. 知 识 图 谱知 识 图 谱知 识 图 谱知 识 图 谱.
 2003 Prentice Hall, Inc. All rights reserved 1 Object-Oriented Programming Inheritance Main Objectives: To understand how inheritance.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 19 - C++ Inheritance Outline 19.1Introduction.
1 、如果 x + 5 > 4 ,那么两边都 可得 x >- 1 2 、在- 3y >- 4 的两边都乘以 7 可得 3 、在不等式 — x≤5 的两边都乘以- 1 可得 4 、将- 7x — 6 < 8 移项可得 。 5 、将 5 + a >- 2 a 移项可得 。 6 、将- 8x < 0.
Chapter 3 Programming Languages Unit 1 The Development of Programming Languages.
UML Class Diagrams 1 These lecture slides are copyright (C) Marty Stepp, They may not be rehosted, sold, or modified without expressed permission.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 20 - C++ Virtual Functions and Polymorphism.
SMIE-121 Software Design II QQ: School of Mobile Information.
§10.2 对偶空间 一、对偶空间与对偶基 二、对偶空间的有关结果 三、例题讲析.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 19 – Inheritance Part 2 Outline 19.8Direct Base Classes and Indirect Base Classes 19.9Using Constructors.
表单自定义 “ 表单自定义 ” 功能是用于制作表单的 工具,用数飞 OA 提供的表单自定义 功能能够快速制作出内容丰富、格 式规范、美观的表单。
CSE 403, Spring 2008, Alverson Using UML to express Software Architecture.
CSE 403, Spring 2007, Alverson Using UML to express Software Architecture.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 9 - Inheritance Outline 9.1Introduction 9.2Inheritance: Base Classes and Derived Classes 9.3.
力的合成 力的合成 一、力的合成 二、力的平行四边形 上一页下一页 目 录 退 出. 一、力的合成 O. O. 1. 合力与分力 我们常常用 一个力来代替几个力。如果这个 力单独作用在物体上的效果与原 来几个力共同作用在物体上的效 果完全一样,那么,这一个力就 叫做那几个力的合力,而那几个 力就是这个力的分力。
SMIE-121 Software Design II School of Mobile Information Engineering, Sun Yat-sen University Lecture.
演示场景. 类图 配置 HibernateApplicationContext.xml hibernate.cfg.xml 创建数据库 – ooad/ooad 关于 Library/Project 模板.
Object-Oriented Design and Programming (Java). 2 Topics Covered Today 2.1 Implementing Classes –2.1.3 Method equals and Method toString –1.2.6 Implementing.
逻辑设计基础 1 第 7 章 多级与(或)非门电路 逻辑设计基础 多级门电路.
 2003 Prentice Hall, Inc. All rights reserved Case Study: Three-Level Inheritance Hierarchy Three level point/circle/cylinder hierarchy –Point.
1 Object-Oriented Programming -- Using C++ Andres, Wen-Yuan Liao Department of Computer Science and Engineering De Lin Institute of Technology
 2000 Prentice Hall, Inc. All rights reserved. Chapter 19 – Inheritance – Part 1 Outline 19.1Introduction 19.2Inheritance: Base Classes and Derived Classes.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 20 - Polymorphism Outline 20.5Polymorphism 20.6Case Study: A Payroll System Using Polymorphism.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 9 - Object-Oriented Programming: Inheritance Outline 9.1 Introduction 9.2 Base Classes and Derived.
Unified Modeling Language (UML)
 2002 Prentice Hall. All rights reserved. Page 1 Inheritance: Object-Oriented Programming Outline 9.1 Introduction 9.2 Superclasses and Subclasses 9.3.
1 Inheritance inheritance –a mechanism that build a new class by deriving from an existing class –derived class (or subclass) inherit from based class.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 9 - Object-Oriented Programming: Inheritance Outline 9.1 Introduction 9.2 Base Classes and Derived.
Session 03 - Templates Outline 03.1Introduction 03.2Function Templates 03.3Overloading Template Functions 03.4Class Templates 03.5Class Templates and Non-type.
Design and UML Class Diagrams
TCSS 305 (Stepp) OO Design with UML Class Diagrams
Chapter 19 - C++ Inheritance
Lecture on Design Phase and UML Class Diagrams
Chapter 6 Reusing Classes.
Chapter 20- Virtual Functions and Polymorphism
Chapter 19 - Inheritance Outline 19.1 Introduction
Chapter 20 - C++ Virtual Functions and Polymorphism
Capitolo 9 - Inheritance
Chapter 19 - Inheritance Outline 19.1 Introduction
Capitolo 10- Virtual Functions and Polymorphism
Chapter 9 - Object-Oriented Programming: Inheritance
Introduction to UML Sources:
Presentation transcript:

SMIE-121 Software Design II School of Mobile Information Engineering, Sun Yat-sen University Lecture 08. C++ Inheritance

Software Design II – C++ Inheritance 2 / 74May 31, 2016 Design and programming are human activities; forget that and all is lost. --Bjarne Stroustrup, 1991

Software Design II – C++ Inheritance 3 / 74May 31, 2016 Outline Introduction Base and derived Classes Types of inheritances Features of inheritance Using of inheritance Software design

Software Design II – C++ Inheritance 4 / 74May 31, 2016 Introduction How to reuse these parts? How to name the student member of a teacher? Anyway, this kind of reuse is weird delegation (has a, uses a, knows a) delegation (has a, uses a, knows a) void Teacher::resetPassword(){ ??.resetPassword(); }

Software Design II – C++ Inheritance 5 / 74May 31, 2016 Introduction How to reuse these parts? inheritance (is a) inheritance (is a) teacher.resetPassword(); student.resetPassword(); Inheritance is a mechanism in OOP for code reusing polymorphism in an Human Naturally Understandable way!

Software Design II – C++ Inheritance 6 / 74May 31, 2016 Inheritance

Software Design II – C++ Inheritance 7 / 74May 31, 2016 Inheritance New classes created from existing classes Absorb( 吸纳 ) attributes and behaviors. Polymorphism Write programs in a general fashion Handle a wide variety of existing (and unspecified) related classes Derived class Class that inherits data members and member functions from a previously defined base class Introduction

Software Design II – C++ Inheritance 8 / 74May 31, 2016 Outline Introduction Base and derived Classes Types of inheritances Features of inheritance Using of inheritance Software design

Software Design II – C++ Inheritance 9 / 74May 31, 2016 Often an object from a derived class (subclass) “is an” object of a base class (superclass) Base and derived classes

class Animal { public: void eat() { cout << "eating“ << endl ; } void sleep() { cout << "sleeping“ << endl ; } void swim() { cout << “swimming“ << endl ; } }; class Bird: public Animal { void fly() { cout << “flying” << endl ; } void swim() { cout << “can not swim” << endl ; } }; Base Class Derived Class int main() { Animal anAnimal ; Bird aBird ; anAnimal.eat() ; anAnimal.swim() ; cout << endl ; aBird.eat() ; aBird.swim() ; aBird.fly() ; return 0 ; } // Derived class can add new members and override the members that Inherited from base class eating swimming eating can not swim flying

Software Design II – C++ Inheritance 11 / 74May 31, 2016 继承与派生 (inheritance & derivation) 继承与派生的概念: 继承:保持已有类的特征而构造新类的过程 派生:在已有类的基础上新增自己的特性而产生新类的过程。 基类和派生类: 基类(或父类):被继承特性的类。 派生类(或子类):新增特性从而派生出的类。 派生类继承了基类, The Student class inherits the User class 基类派生出派生类, The User class derives the Student class 继承与派生的目的: 继承的目的:实现代码重用。 派生的目的:在不改变原有程序的情况下,对原有程序进行改 造。(多态: polymorphism )

Software Design II – C++ Inheritance 12 / 74May 31, 2016 派生类生产的过程 步骤: 吸收基类成员 — 代码重用的过程 改造基类成员 添加新的成员 1. 吸收基类成员: 派生类包含了它的所有基类中除构造与析构函数之外的 所有成员。 2. 改造基类成员: ( 1 )对基类成员的访问控制 —— 依靠派生类声明时的 继承方式来控制。 ( 2 )对基类数据或函数成员的覆盖。 3. 添加新的成员(继承与派生机制的核心) -- 原有代码的扩充过程

Software Design II – C++ Inheritance 13 / 74May 31, 2016 What a derived class can't inherit ? ( 1 ) The base class's constructors and destructors ( 2 ) The base class's assignment operators ( 3 ) The base class's friend functions What a derived class can add ? ( 1 ) New data members ( 2 ) New member functions ( 3 ) New constructors and destructors ( 4 ) New friend functions Base and derived classes

Software Design II – C++ Inheritance 14 / 74May 31, 2016 Outline Introduction Base and derived Classes Types of inheritances Features of inheritance Using of inheritance Software design

Software Design II – C++ Inheritance 15 / 74May 31, 2016 private :只能在 (1) 该类方法、 (2) 其友元函数中访 问。 protected :可以在 (1) 该类方法、 (2) 子类方法、 (3) 其友元函数中访问。 public :可以被所有代码通过对象成员访问运算 (. - >) 访问 Access control: private protected public

Software Design II – C++ Inheritance 16 / 74May 31, 2016 Public Inheritance: Publicly accessible members inherited from the base class stay publicly accessible in the derived class. Private Inheritance: Publicly accessible members inherited from the base class stay private in the derived class. Protected Inheritance: Data members which are not publicly accessible, but are accessible to derived classes. Public private protected inheritance

Software Design II – C++ Inheritance 17 / 74May 31, 2016 private 属性不能够被继承。 使用 private 继承,父类的 protected 和 public 属性在子类中变 为 private ; 使用 protected 继承,父类的 protected 和 public 属性在子类中 变为 protected ; 使用 public 继承,父类中的 protected 和 public 属性不发生改变 ; Public private protected inheritance

Software Design II – C++ Inheritance 18 / 74May 31, 2016 类成员共有三种级别的继承 :public , protected 和 private 。对于基 类成员的存取操作应该依赖于下面两个因素 : 1) 派生类声明其类头 (public, protected 或 private) 的方式 2) 对类成员的存取访问标志 (public, protected 或 private) 基类(父类)的访问特性类的继承特性派生类(子类)的访问特性 Public Protected Private Public Protected No access Public Protected Private Protected No access Public Protected Private No access Public private protected inheritance Always (99%) use public inheritance only unless it can’t solve your problem, and think twice before using protected or private

Software Design II – C++ Inheritance 19 / 74May 31, 2016 Inheritance Single Inheritance Class inherits from one base class Multiple Inheritance Class inherits from multiple base classes Single and multiple inheritance Always (99%) use single inheritance only unless it can’t solve your problem, and think twice before using multiple inheritance

Software Design II – C++ Inheritance 20 / 74May 31, 2016 Direct base class Explicitly listed derived class’ header with the colon ( : ) notation when that derived class is declared. class HourlyWorker : public Employee Employee is a direct base class of HourlyWorker Indirect base class Inherited from two or more levels up the class hierarchy class MinuteWorker : public HourlyWorker Employee is an indirect base class of MinuteWorker Direct and indirect base class

employ.h 2 // Definition of class Employee 3 #ifndef EMPLOY_H 4 #define EMPLOY_H 5 6 class Employee { 7 public: 8 Employee( const char *, const char * ); // constructor 9 void print() const; // output first and last name 10 ~Employee(); // destructor 11 private: 12 char *firstName; // dynamically allocated string 13 char *lastName; // dynamically allocated string 14 }; // end class Employee 16 #endif 17 // Fig. 6.5: employ.cpp 18 // Member function definitions for class Employee 19 #include using std::cout; #include 24 #include 25 #include "employ.h" employ.cpp (1 of 2)

employ.cpp (2 of 2) 27 // Constructor dynamically allocates space for the 28 // first and last name and uses strcpy to copy 29 // the first and last names into the object. 30 Employee::Employee( const char *first, const char *last ) 31 { 32 firstName = new char[ strlen( first ) + 1 ]; 33 assert( firstName != 0 ); // terminate if not allocated 34 strcpy( firstName, first ); lastName = new char[ strlen( last ) + 1 ]; 37 assert( lastName != 0 ); // terminate if not allocated 38 strcpy( lastName, last ); 39 } // end Employee constructor // Output employee name 42 void Employee::print() const 43 { cout << firstName << ' ' << lastName; } // Destructor deallocates dynamically allocated memory 46 Employee::~Employee() 47 { 48 delete [] firstName; // reclaim dynamic memory 49 delete [] lastName; // reclaim dynamic memory 50 } // end Employee destructor

hourly.h 51 // Fig. 6.5: hourly.h 52 // Definition of class HourlyWorker 53 #ifndef HOURLY_H 54 #define HOURLY_H #include "employ.h" class HourlyWorker : public Employee { 59 public: 60 HourlyWorker( const char*, const char*, double, double ); 61 double getPay() const; // calculate and return salary 62 void print() const; // overridden base-class print 63 private: 64 double wage; // wage per hour 65 double hours; // hours worked for week 66 }; // end class HourlyWorker #endif 69 // Fig. 6.5: hourly.cpp 70 // Member function definitions for class HourlyWorker 71 #include using std::cout; 74 using std::endl; #include hourly.cpp (1 of 2)

hourly.cpp (2 of 2) 78 using std::ios; 79 using std::setiosflags; 80 using std::setprecision; 82 #include "hourly.h" // Constructor for class HourlyWorker 85 HourlyWorker::HourlyWorker( const char *first, 86 const char *last, 87 double initHours, double initWage ) 88 : Employee( first, last ) // call base-class constructor 89 { 90 hours = initHours; // should validate 91 wage = initWage; // should validate 92 } // end HourlyWorker constructor // Get the HourlyWorker's pay 95 double HourlyWorker::getPay() const { return wage * hours; } // Print the HourlyWorker's name and pay 98 void HourlyWorker::print() const 99 { 100 cout << "HourlyWorker::print() is executing\n\n"; 101 Employee::print(); // call base-class print function cout << " is an hourly worker with pay of $" 104 << setiosflags( ios::fixed | ios::showpoint ) 105 << setprecision( 2 ) << getPay() << endl; 106 } // end function print

fig19_05.cpp 107 // Fig. 6.5: fig19_05.cpp 108 // Overriding a base-class member function in a 109 // derived class. 110 #include "hourly.h" int main() 113 { 114 HourlyWorker h( "Bob", "Smith", 40.0, ); 115 h.print(); 116 return 0; 117 } // end function main HourlyWorker::print() is executing Bob Smith is an hourly worker with pay of $400.00

Software Design II – C++ Inheritance 26 / 74May 31, 2016 Outline Introduction Base and derived Classes Types of inheritances Features of inheritance Using of inheritance Software design

Software Design II – C++ Inheritance 27 / 74May 31, 2016 To hide a base-class member function In derived class, supply new version of that function Same function name, different definition 会屏蔽基类同名函数,即使函数原型不同也会被屏蔽。如 : class Base { public: void fun(); }; class Derived : public Base { public: void fun(int ); }; Derived d; Base b; b.fun();// 正确 d.fun(1);// 正确 d.fun();// 错误,没有参数的 fun() 函数被屏蔽了 The scope-resolution operator may be used to access the base class version from the derived class 比如上面的例子,可以通过 d.Base::fun() 来访问 Base 中的 fun() 或者在 Derived 定义中使用 using Base:fun(), 让 Derived 拥有一对重载方法 fun Method hiding

Software Design II – C++ Inheritance 28 / 74May 31, 2016 Base class initializer Uses member-initializer syntax Can be provided in the derived class constructor to call the base-class constructor explicitly Otherwise base class’ default constructor called implicitly Base-class constructors and base-class assignment operators are not inherited by derived classes However, derived-class constructors and assignment operators still can call them Constructors and deconstructors

Software Design II – C++ Inheritance 29 / 74May 31, 2016 Derived-class constructor Calls the constructor for its base class first to initialize its base-class members If the derived-class constructor is omitted, its default constructor calls the base-class’ default constructor Destructors are called in the reverse order of constructor calls Derived-class destructor is called before its base-class destructor Constructors and deconstructors

point2.h 1 // Fig. 6.7: point2.h 2 // Definition of class Point 3 #ifndef POINT2_H 4 #define POINT2_H 5 6 class Point { 7 public: 8 Point( int = 0, int = 0 ); // default constructor 9 ~Point(); // destructor 10 protected: // accessible by derived classes 11 int x, y; // x and y coordinates of Point 12 }; // end class Point #endif

point2.cpp 15 // Fig. 6.7: point2.cpp 16 // Member function definitions for class Point 17 #include using std::cout; 20 using std::endl; #include "point2.h" 24 // Constructor for class Point 25 Point::Point( int a, int b ) 26 { 27 x = a; 28 y = b; cout << "Point constructor: " 31 << '[' << x << ", " << y << ']' << endl; 32 } // end Point constructor // Destructor for class Point 35 Point::~Point() 36 { 37 cout << "Point destructor: " 38 << '[' << x << ", " << y << ']' << endl; 39 } // end Point destructor

circle2.h 40 // Fig. 6.7: circle2.h 41 // Definition of class Circle 42 #ifndef CIRCLE2_H 43 #define CIRCLE2_H #include "point2.h" class Circle : public Point { 48 public: 49 // default constructor 50 Circle( double r = 0.0, int x = 0, int y = 0 ); ~Circle(); 53 private: 54 double radius; 55 }; // end class Circle #endif

circle2.cpp 58 // Fig. 6.7: circle2.cpp 59 // Member function definitions for class Circle 60 #include using std::cout; 63 using std::endl; #include "circle2.h" // Constructor for Circle calls constructor for Point 68 Circle::Circle( double r, int a, int b ) 69 : Point( a, b ) // call base-class constructor 70 { 71 radius = r; // should validate 72 cout << "Circle constructor: radius is " 73 << radius << " [" << x << ", " << y << ']' << endl; 74 } // end Circle constructor // Destructor for class Circle 77 Circle::~Circle() 78 { 79 cout << "Circle destructor: radius is " 80 << radius << " [" << x << ", " << y << ']' << endl; 81 } // end Circle destructor

fig19_07.cpp (1 of 2) 82 // Fig. 6.7: fig19_07.cpp 83 // Demonstrate when base-class and derived-class 84 // constructors and destructors are called. 85 #include 87 using std::cout; 88 using std::endl; #include "point2.h" 91 #include "circle2.h" int main() 94 { 95 // Show constructor and destructor calls for Point 96 { 97 Point p( 11, 22 ); 98 } // end block 100 cout << endl; 101 Circle circle1( 4.5, 72, 29 ); 102 cout << endl; 103 Circle circle2( 10, 5, 5 ); 104 cout << endl; 105 return 0; 106 } // end function main

fig19_07.cpp (2 of 2) Point constructor: [11, 22] Point destructor: [11, 22] Point constructor: [72, 29] Circle constructor: radius is 4.5 [72, 29] Point constructor: [5, 5] Circle constructor: radius is 10 [5, 5] Circle destructor: radius is 10 [5, 5] Point destructor: [5, 5] Circle destructor: radius is 4.5 [72, 29] Point destructor: [72, 29]

Software Design II – C++ Inheritance 36 / 74May 31, 2016 baseClassObject = derivedClassObject; This will work 原因是父类对象中的除私有外的数据成员都能在子类对 象中找到对应。 Extra data is not given to the base class 基类的私有数据成员也不会被赋值 Type conversion

Software Design II – C++ Inheritance 37 / 74May 31, 2016 derivedClassObject = baseClassObject; May not work properly Unless an assignment operator is overloaded in the derived class, data members exclusive to the derived class will be unassigned 主要原因是那些派生类对象中新添加的数据成员在父类对象 中找不到对应的数据成员。 Type conversion

Software Design II – C++ Inheritance 38 / 74May 31, 2016 Four ways to mix base and derived class pointers and objects: Referring to a base-class object with a base-class pointer Allowed Referring to a derived-class object with a derived-class pointer Allowed Referring to a derived-class object with a base-class pointer It is Safe but need to be used carefully 但是只能引用基类成员。因为名字查找是在编译时发生的,对象、引用或 指针的静态类型决定了对象能够完成的行为。若试图通过基类指针引用那 些只在派生类中才有的成员,编译器会报告语法错误。 (下章虚函数会 详细解释) Referring to a base-class object with a derived-class pointer Syntax error The derived-class pointer must first be cast to a base-class pointer Pointers of derived and base classes

Software Design II – C++ Inheritance 39 / 74May 31, 2016 Outline Introduction Base and derived Classes Types of inheritances Features of inheritance Using of inheritance Software design

Software Design II – C++ Inheritance 40 / 74May 31, 2016 Classes are often closely related “Factor out” ( 提取 ) common attributes and behaviors and place these in a base class Use inheritance to form derived classes Modifications to a base class Derived classes do not change as long as the public and protected interfaces are the same Derived classes may need to be recompiled Using inheritance

Software Design II – C++ Inheritance 41 / 74May 31, 2016 "is a" relationship Inheritance "has a" relationship Association - class has an object from another class as a data member Employee “is a” BirthDate; //Wrong! Employee “has a” BirthDate;//Composition Association vs. Inheritance

Software Design II – C++ Inheritance 42 / 74May 31, 2016 Define class Point Derive Circle Derive Cylinder Case study Point, Circle, Cylinder

point2.h 1 // Fig. 6.8: point2.h 2 // Definition of class Point 3 #ifndef POINT2_H 4 #define POINT2_H 5 6 #include 7 8 using std::ostream; 9 10 class Point { 11 friend ostream &operator<<( ostream &, const Point & ); 12 public: 13 Point( int = 0, int = 0 ); // default constructor 14 void setPoint( int, int ); // set coordinates 15 int getX() const { return x; } // get x coordinate 16 int getY() const { return y; } // get y coordinate 17 protected: // accessible to derived classes 18 int x, y; // coordinates of the point 19 }; // end class Point #endif

point2.cpp 22 // Fig. 6.8: point2.cpp 23 // Member functions for class Point 24 #include "point2.h" // Constructor for class Point 27 Point::Point( int a, int b ) { setPoint( a, b ); } // Set the x and y coordinates 30 void Point::setPoint( int a, int b ) 31 { 32 x = a; 33 y = b; 34 } // end function setPoint // Output the Point 37 ostream &operator<<( ostream &output, const Point &p ) 38 { 39 output << '[' << p.x << ", " << p.y << ']'; return output; // enables cascading 42 } // end operator<< function

fig19_08.cpp 43 // Fig. 6.8: fig19_08.cpp 44 // Driver for class Point 45 #include 47 using std::cout; 48 using std::endl; 50 #include "point2.h" int main() 53 { 54 Point p( 72, 115 ); // instantiate Point object p 56 // protected data of Point inaccessible to main 57 cout << "X coordinate is " << p.getX() 58 << "\nY coordinate is " << p.getY(); p.setPoint( 10, 10 ); 61 cout << "\n\nThe new location of p is " << p << endl; return 0; 64 } // end function main X coordinate is 72 Y coordinate is 115 The new location of p is [10, 10]

circle2.h 1 // Fig. 6.9: circle2.h 2 // Definition of class Circle 3 #ifndef CIRCLE2_H 4 #define CIRCLE2_H 5 6 #include 7 8 using std::ostream; 9 10 #include "point2.h" class Circle : public Point { 13 friend ostream &operator<<( ostream &, const Circle & ); 14 public: 15 // default constructor 16 Circle( double r = 0.0, int x = 0, int y = 0 ); 17 void setRadius( double ); // set radius 18 double getRadius() const; // return radius 19 double area() const; // calculate area 20 protected: // accessible to derived classes 21 double radius; // radius of the Circle 22 }; // end class Circle #endif

circle2.cpp (1 of 2) 25 // Fig. 6.9: circle2.cpp 26 // Member function definitions for class Circle 27 #include 29 using std::ios; 30 using std::setiosflags; 31 using std::setprecision; #include "circle2.h" 35 // Constructor for Circle calls constructor for Point 36 // with a member initializer and initializes radius 37 Circle::Circle( double r, int a, int b ) 38 : Point( a, b ) // call base-class constructor 39 { setRadius( r ); } 41 // Set radius 42 void Circle::setRadius( double r ) 43 { radius = ( r >= 0 ? r : 0 ); } // Get radius 46 double Circle::getRadius() const { return radius; } // Calculate area of Circle 49 double Circle::area() const 50 { return * radius * radius; }

circle2.cpp (2 of 2) 52 // Output a circle in the form: 53 // Center = [x, y]; Radius = #.## 54 ostream &operator<<( ostream &output, const Circle &c ) 55 { 56 output ( c ) 57 << "; Radius = " 58 << setiosflags( ios::fixed | ios::showpoint ) 59 << setprecision( 2 ) << c.radius; return output; // enables cascaded calls 62 } // end operator<< function 63 // Fig. 6.9: fig19_09.cpp 64 // Driver for class Circle 65 #include using std::cout; 68 using std::endl; #include "point2.h" 71 #include "circle2.h" 72 fig19_09.cpp (1 of 2)

fig19_09.cpp (2 of 2) 73 int main() 74 { 75 Circle c( 2.5, 37, 43 ); 77 cout << "X coordinate is " << c.getX() 78 << "\nY coordinate is " << c.getY() 79 << "\nRadius is " << c.getRadius(); 81 c.setRadius( 4.25 ); 82 c.setPoint( 2, 2 ); 83 cout << "\n\nThe new location and radius of c are\n" 84 << c << "\nArea " << c.area() << '\n'; 86 Point &pRef = c; 87 cout << "\nCircle printed as a Point is: " << pRef << endl; return 0; 90 } // end function main X coordinate is 37 Y coordinate is 43 Radius is 2.5 The new location and radius of c are Center = [2, 2]; Radius = 4.25 Area Circle printed as a Point is: [2, 2]

cylindr2.h 1 // Fig. 6.10: cylindr2.h 2 // Definition of class Cylinder 3 #ifndef CYLINDR2_H 4 #define CYLINDR2_H 5 6 #include 8 using std::ostream; 10 #include "circle2.h" class Cylinder : public Circle { 13 friend ostream &operator<<( ostream &, const Cylinder & ); 15 public: 16 // default constructor 17 Cylinder( double h = 0.0, double r = 0.0, 18 int x = 0, int y = 0 ); void setHeight( double ); // set height 21 double getHeight() const; // return height 22 double area() const; // calculate and return area 23 double volume() const; // calculate and return volume protected: 26 double height; // height of the Cylinder 27 }; // end class Cylinder #endif

cylindr2.cpp (1 of 2) 30 // Fig. 6.10: cylindr2.cpp 31 // Member and friend function definitions 32 // for class Cylinder. 33 #include "cylindr2.h" 35 // Cylinder constructor calls Circle constructor 36 Cylinder::Cylinder( double h, double r, int x, int y ) 37 : Circle( r, x, y ) // call base-class constructor 38 { setHeight( h ); } // Set height of Cylinder 41 void Cylinder::setHeight( double h ) 42 { height = ( h >= 0 ? h : 0 ); } // Get height of Cylinder 45 double Cylinder::getHeight() const { return height; } // Calculate area of Cylinder (i.e., surface area) 48 double Cylinder::area() const 49 { 50 return 2 * Circle::area() * * radius * height; 52 } // end function area // Calculate volume of Cylinder 55 double Cylinder::volume() const 56 { return Circle::area() * height; }

cylindr2.cpp (2 of 2) 58 // Output Cylinder dimensions 59 ostream &operator<<( ostream &output, const Cylinder &c ) 60 { 61 output ( c ) 62 << "; Height = " << c.height; return output; // enables cascaded calls 65 } // end operator<< function fig19_10.cpp (1 of 3) 66 // Fig. 6.10: fig19_10.cpp 67 // Driver for class Cylinder 68 #include 70 using std::cout; 71 using std::endl; #include "point2.h" 74 #include "circle2.h" 75 #include "cylindr2.h" int main() 78 { 79 // create Cylinder object 80 Cylinder cyl( 5.7, 2.5, 12, 23 );

fig19_10.cpp (2 of 3) 82 // use get functions to display the Cylinder 83 cout << "X coordinate is " << cyl.getX() 84 << "\nY coordinate is " << cyl.getY() 85 << "\nRadius is " << cyl.getRadius() 86 << "\nHeight is " << cyl.getHeight() << "\n\n"; // use set functions to change the Cylinder's attributes 89 cyl.setHeight( 10 ); 90 cyl.setRadius( 4.25 ); 91 cyl.setPoint( 2, 2 ); 92 cout << "The new location, radius, and height of cyl are:\n" 93 << cyl << '\n'; cout << "The area of cyl is:\n" 96 << cyl.area() << '\n'; // display the Cylinder as a Point 99 Point &pRef = cyl; // pRef "thinks" it is a Point 100 cout << "\nCylinder printed as a Point is: " 101 << pRef << "\n\n"; // display the Cylinder as a Circle 104 Circle &circleRef = cyl; // circleRef thinks it is a Circle 105 cout << "Cylinder printed as a Circle is:\n" << circleRef 106 << "\nArea: " << circleRef.area() << endl; return 0; 109 } // end function main

fig19_10.cpp (3 of 3) X coordinate is 12 Y coordinate is 23 Radius is 2.5 Height is 5.7 The new location, radius, and height of cyl are: Center = [2, 2]; Radius = 4.25; Height = The area of cyl is: Cylinder printed as a Point is: [2, 2] Cylinder printed as a Circle is: Center = [2, 2]; Radius = 4.25 Area: 56.74

Software Design II – C++ Inheritance 55 / 74May 31, 2016 Outline Introduction Base and derived Classes Types of inheritances Features of inheritance Using of inheritance Software design

Software Design II – C++ Inheritance 56 / 74May 31, 2016 Software Design Software design is a phase or a discipline of a software process Software Design: Specifying the structure of how a software system will be written and function (without actually writing the code). A transition from "what" the system must do, to "how" the system will do it What classes will we need in order to implement a system that meets our requirements? What fields and methods will each class have? How will the classes interact with each other?

Software Design II – C++ Inheritance 57 / 74May 31, 2016 How Do We Design Classes? Class identification from project spec / requirements Nouns are potential classes, objects, fields Verbs are potential methods or responsibilities of a class CRC card exercises Write down classes' names on index cards Next to each class, list the following: Responsibilities: problems to be solved; short verb phrases Collaborators: other classes that are sent messages by this class (asymmetric) UML Class diagrams Sequence diagrams...

Software Design II – C++ Inheritance 58 / 74May 31, 2016 Introduction to UML Unified Modeling Language (UML): depicts an OO system Programming languages are not abstract enough for OO design UML is an open standard; lots of companies use it Many programmers either know UML or a "UML-like" variant UML is... A descriptive language: rigid formal syntax (like programming) A prescriptive language: shaped by usage and convention UML has a rigid syntax, but some don't follow it religiously It's okay to omit things from UML diagrams if they aren't needed by team/supervisor/instructor

Software Design II – C++ Inheritance 59 / 74May 31, 2016 UML Class Diagrams What is a UML class diagram? What does it represent? UML class diagram: A picture of the classes in an OO system, their fields and methods, and connections between the classes that interact or inherit from each other. What are some things not represented in a class diagram? Details of how the classes interact Algorithmic details; how particular behavior is implemented Trivial methods ( get / set ) Classes that come from libraries ( ArrayList, etc.)

Software Design II – C++ Inheritance 60 / 74May 31, 2016 Class Diagram class name attributes methods composition dependency, friend function Align elements as possible No cross lines, no diagonal lines

Software Design II – C++ Inheritance 61 / 74May 31, 2016 Diagram of One Class Class name in top of box Write > on top of interfaces' names Use italics for an abstract class name Attributes Should include all fields of the object Also includes derived "properties" Operations / Methods May omit trivial (get/set) methods But don't omit any methods from an interface! Should not include inherited methods

Software Design II – C++ Inheritance 62 / 74May 31, 2016 Class Attributes Attributes (fields, instance variables) visibility name : type [count ] = defaultValue Visibility: + public # protected - private ~ package (default) / derived Underline static attributes Derived attribute: not stored, but can be computed from other attribute values Attribute example: - balance : double = 0.00

Software Design II – C++ Inheritance 63 / 74May 31, 2016 Class Operations / Methods Operations / Methods visibility name (parameters ) : returnType Underline static methods Parameter types listed as (name: type) Omit returnType on constructors and when return is void Method example: + distance(p1: Point, p2: Point): double

Software Design II – C++ Inheritance 64 / 74May 31, 2016 Comments Represented as a folded note, attached to the appropriate class/method/etc by a dashed line

Software Design II – C++ Inheritance 65 / 74May 31, 2016 Relationships btwn. Classes Generalization: an inheritance relationship Inheritance between classes Interface implementation Association: a usage relationship Dependency Aggregation Composition

Software Design II – C++ Inheritance 66 / 74May 31, 2016 Generalization Relationships Hierarchies drawn top-down with arrows pointing upward to parent Line/Arrow styles differ based on parent: class :solid, black arrow abstract class :solid, white arrow interface :dashed, white arrow We often don't draw trivial / obvious relationships, such as drawing the class Object as a parent

Software Design II – C++ Inheritance 67 / 74May 31, 2016 Associational Relationships 1. Multiplicity (how many are used) *  0, 1, or more 1  1 exactly 2..4  between 2 and 4, inclusive 3..*  3 or more 2. Name (what relationship the objects have) 3. Navigability(direction)

Software Design II – C++ Inheritance 68 / 74May 31, 2016 Multiplicity One-to-one Each student must have exactly one ID card One-to-many A RectangleList can contain 0, 1, 2,... rectangles

Software Design II – C++ Inheritance 69 / 74May 31, 2016 Association Types Aggregation: "is part of" clear white diamond Composition: "is entirely made of" stronger version of aggregation the parts live and die with the whole black diamond Dependency: "uses temporarily" dotted line or arrow often is an implementation detail, not an intrinsic part of that object's state 1 1 aggregation Car Engine Lottery Ticket Random dependency Page Book composition * 1

Software Design II – C++ Inheritance 70 / 74May 31, 2016 Class Diagram Example 1 DON’T use diagonal line!

Software Design II – C++ Inheritance 71 / 74May 31, 2016 Class Diagram Example 2 DVD MovieVHS MovieVideo Game Rental Item Rental Invoice 1..* 1 Customer Checkout Screen Simple Association Class Abstract Class Simple Aggregation Generalization Composition Multiplicity

Software Design II – C++ Inheritance 72 / 74May 31, 2016 Class Diagram Example 3 StudentBody + main (args : String[]) + toString() : String 1100 Student - firstName : String - lastName : String - homeAddress : Address - schoolAddress : Address + toString() : String - streetAddress : String - city : String - state : String - zipCode : long Address

Software Design II – C++ Inheritance 73 / 74May 31, 2016 Tools for UML Umlet (free, and recommended) Violet (free) Rational Rose Visual Paradigm UML Suite (trial) (nearly) direct download link: (There are many others, but many are commercial and cost money)

Software Design II – C++ Inheritance 74 / 74May 31, 2016 Thank you!