C++ Programming: Inheritance

Similar documents
INHERITANCE - Part 1. CSC 330 OO Software Design 1

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

INHERITANCE - Part 1. CSC 330 OO Software Design 1

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

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

C++ Programming: Polymorphism

1. the base class s (default) constructor is executed first, 2. followed by the derived class s constructor

Inheritance -- Introduction

CLASSES AND OBJECTS IN JAVA

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

C++ Programming: Introduction to C++ and OOP (Object Oriented Programming)

Object Oriented Features. Inheritance. Inheritance. CS257 Computer Science I Kevin Sahr, PhD. Lecture 10: Inheritance

Inheritance, and Polymorphism.

POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors

POLYMORPHISM 2 PART. Shared Interface. Discussions. Abstract Base Classes. Abstract Base Classes and Pure Virtual Methods EXAMPLE

Data Abstraction. Hwansoo Han

Inheritance. Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L

CS105 C++ Lecture 7. More on Classes, Inheritance

ECE 122. Engineering Problem Solving with Java

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

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

CS250 Final Review Questions

Polymorphism Part 1 1

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming

What are the characteristics of Object Oriented programming language?

Written by John Bell for CS 342, Spring 2018

CS250 Final Review Questions

Lecture 18 CSE11 Fall 2013 Inheritance

VIRTUAL FUNCTIONS Chapter 10

Inheritance (Deitel chapter 9)

Chapter 6 Reflection

private: // can only be used by the member functions of MyType and friends of MyType };

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.

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

CS-202 Introduction to Object Oriented Programming

Derived Classes in C++

Derived and abstract data types. TDT4205 Lecture 15

Inheritance and Polymorphism

Inheritance, Polymorphism and the Object Memory Model

G Programming Languages - Fall 2012

CMSC 132: Object-Oriented Programming II

Programming Language Concepts Object-Oriented Programming. Janyl Jumadinova 28 February, 2017

Chapter 6 Introduction to Defining Classes

Programming C++ Lecture 3. Howest, Fall 2012 Instructor: Dr. Jennifer B. Sartor

1B1b Inheritance. Inheritance. Agenda. Subclass and Superclass. Superclass. Generalisation & Specialisation. Shapes and Squares. 1B1b Lecture Slides

Java Object Oriented Design. CSC207 Fall 2014

Ch 14. Inheritance. May 14, Prof. Young-Tak Kim

Lecture 10: Introduction to Inheritance

THE NAME OF THE CONSTRUCTOR AND DESTRUCTOR(HAVING (~) BEFORE ITS NAME) FUNCTION MUST BE SAME AS THE NAME OF THE CLASS IN WHICH THEY ARE DECLARED.

History C++ Design Goals. How successful? Significant constraints. Overview of C++

C++ Crash Kurs. Polymorphism. Dr. Dennis Pfisterer Institut für Telematik, Universität zu Lübeck

CMSC 132: Object-Oriented Programming II

Computer Programming Inheritance 10 th Lecture

Java: introduction to object-oriented features

C++ Yanyan SHEN. slide 1

Inheritance CSC 123 Fall 2018 Howard Rosenthal

CSC207H: Software Design. Java + OOP. CSC207 Winter 2018

CS11 Introduction to C++ Fall Lecture 7

Intro to OOP Visibility/protection levels and constructors Friend, convert constructor, destructor Operator overloading a<=b a.

Inheritance Chapter 8. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

OOPS Viva Questions. Object is termed as an instance of a class, and it has its own state, behavior and identity.

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

Programming, numerics and optimization

Programming in C# Inheritance and Polymorphism

Object-Oriented Programming, Iouliia Skliarova

Exercise: Singleton 1

ITI Introduction to Computing II

C++ Inheritance and Encapsulation

Abstract Data Types (ADT) and C++ Classes

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

Outline. User-dened types Categories. Constructors. Constructors. 4. Classes. Concrete classes. Default constructor. Default constructor

Argument Passing All primitive data types (int etc.) are passed by value and all reference types (arrays, strings, objects) are used through refs.

Comp 249 Programming Methodology

CSC1322 Object-Oriented Programming Concepts

Programming II (CS300)

Inheritance. Transitivity

11/19/2014. Inheritance. Chapter 7: Inheritance. Inheritance. Inheritance. Java Software Solutions for AP* Computer Science A 2nd Edition

Building custom components IAT351

ITI Introduction to Computing II

Instructions. Quiz #2. Name: Solutions Student Number: Signature:

Objects and Classes: Working with the State and Behavior of Objects

Overriding המחלקה למדעי המחשב עזאם מרעי אוניברסיטת בן-גוריון

What s Conformance? Conformance. Conformance and Class Invariants Question: Conformance and Overriding

Chapter 10 Classes Continued. Fundamentals of Java

What is Inheritance?

Software Paradigms (Lesson 3) Object-Oriented Paradigm (2)

Inheritance. Quick Review of Last Lecture. November 12, Passing Arguments. Passing Arguments. Variable Assignment Revisited

CS250 Final Review Questions

Data Structures and Other Objects Using C++

Inheritance Motivation

Introduction to Inheritance

ASSIGNMENT NO 13. Objectives: To learn and understand concept of Inheritance in Java

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

Instance Members and Static Members

Fast Introduction to Object Oriented Programming and C++

Instantiation of Template class

Objects, Encapsulation, Inheritance (2)

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

CSC207H: Software Design. Java + OOP. CSC207 Winter 2018

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.

Transcription:

C++ Programming: Inheritance 2018 년도 2 학기 Instructor: Young-guk Ha Dept. of Computer Science & Engineering

Contents Basics on inheritance C++ syntax for inheritance protected members Constructors and destructors in inheritance Multiple inheritance 2

Inheritance What is inheritance? The heart of OO programming A mechanism to build a new class by deriving the new class from already existing base classes Single inheritance: inherits from one base class Multiple inheritance: inherits from more than two base classes Basic data members and methods for students (e.g., name, student_no, dept, and so on) Student Base class (also called superclass or parent class) Content of a derived class Data members and methods inherited from the base classes Except for constructors and destructors Additional data members and methods specific to the derived class Inherited methods can be overridden GradStudent Additional data members and methods specific to graduate students can be defined (e.g., advisor, degree_course, thesis_title, and so on) Derived class (subclass or child class) 3

Benefits of Inheritance Inheritance promotes code reuse and robustness The code (data and methods) in the base class is inherited to the subclass Inherited code needs not be rewritten Reducing the amount of code to be newly created If the code from the base class is correct, it will also correct in the derived class Bugs might be reduced robustness Expression of class relationship Provides a mechanism to naturally express is a relationships among classes that are modules of OO programing E.g., a GradStudent is a Student is a relationship is precisely mirrored in the code with inheritance 4

Specialization Generalization Class Hierarchy A derived class can serve as a base class for other classes by itself And those classes can also be base classes, Vehicle direct base class of Car indirect base class of Bus This relationship is called class hierarchy (a.k.a. inheritance hierarchy) When we move down the hierarchy, each class is a specialized version of its base class Car direct derived class of Vehicle direct base class of Bus When we move up the hierarchy, each class is a generalized version of its derived class Bus direct derived class of Car indirect derived class of Vehicle 5

C++ Syntax of Inheritance Three types of inheritance to derive class DC from class BC Private inheritance (default) Class DC : BC { = Class DC : private BC { private can be specified explicitly Public inheritance (most frequently used) Class DC : public BC { Protected inheritance Class DC : protected BC { 6

Access Modifiers in Inheritance Public inheritance In the Base Class private protected public In the Derived Class invisible protected public Private (default) inheritance In the Base Class private protected public In the Derived Class invisible private private Protected inheritance In the Base Class private protected public In the Derived Class invisible protected protected 7

Public Inheritance Example class Pen { void set_status(bool s); void set_location(int x, int y); int x; int y; bool status; class CPen : public Pen { void set_color(int c); int color; CPen cp; // creates a CPen object cp cp.set_location(100, 200); cp.set_status(true); cp.set_color(123) CPen (colored pen) class [Pen] [CPen] Inherits all the data members and methods from class Pen Public methods set_status and set_location of Pen are also public in CPen Defines data member color and method set_color x y status set_status set_location x invisible y status set_status set_location color set_color Base class from class [Pen] Derived class 8

Protected and Private Inheritance Examples class BC { void set_x(int a) { } protected: int get_x() const { } int x; Member of BC set_x get_x x Access status in protected inheritance Access status in class BC public protected private Access status in DC1 protected protected Not accessible // protected inheritance class DC1 : protected BC { // private inheritance class DC2 : private BC { Member of BC set_x get_x x Access status in private inheritance Access status in class BC public protected private Access status in DC2 private private Not accessible 9

Accessing private Members of Base Classes Each private member in a base class is visible only in the base class I.e., Even though private members are inherited by derived classes, they are NOT visible in the derived classes class Point { void set_x(const int x1) { x = x1; } void set_y(const int y1) { y = y1; } int get_x() const { return x; } int get_y() const { return y; } int x; int y; class Intense_Point : public Point { void set_intensity(const int i) { intens = i; } int get_intensity() const { return intens; } int intens; Class Intense_Point It inherits data member x and y from Point, which are only visible in Point One can indirectly access x and y through the public methods set_x, set_y, get_x, and get_y inherited from Point 10

Members of Intense_Point Members Access status within Intense_Point How obtained x y set_x set_y get_x get_y intensity set_intensity get_intensity Not accessible* Not accessible** public public public public private public Public Inherited from class Point Inherited from class Point Inherited from class Point Inherited from class Point Inherited from class Point Inherited from class Point Defined in class Intense_Point Defined in class Intense_Point Defined in class Intense_Point * Indirectly accessible through method set_x and get_x ** Indirectly accessible through method set_y and get_y 11

Restricting Access to Inherited public Members Normally, public members in a base class would be inherited as public However, sometimes access to those inherited public members from outside needs to be disabled This can be done by changing the access status of the inherited members to private with using declaration and private modifier class BC { void set_x(float a) { x = a; } float x; class DC : public BC { void set_y(float b) { y = b; } float y; using BC::set_x; int main() { DC d; } d.set_y(4.31); // OK d.set_x(-8.03); // error: set_x is private in DC 12

Name Hiding Name hiding: when a derived class adds a new method with the same name as one of inherited methods (but with different signatures), the new method hides the inherited method Name hiding a kind of name conflict Cf. method overriding: when the new method and the inherited method have the same signature Cf. method overloading: when both methods are defined in the same class and have the same signature class BC { void h(float); // BC::h void main() { DC d1; d1.h("boffo! ); // DC::h, not BC::h class DC : public BC { void h(char *); // hides h(float) from BC } d1.h(707.7); // ERROR: DC::h hides BC::h d1.bc::h(707.7); // OK: BC::h is invoked 13

Indirect Inheritance Data members and methods may traverse several inheritance links as they are included from a base to a derived class Thus, inheritance may be either direct or indirect Direct inheritance From a direct base class to a derived class E.g., parent child Indirect inheritance From a indirect base class to a derived class E.g., grand_parent parent child Note that public members remain public throughout the chain of public inheritance links 14

Indirect Inheritance Example class Animal { string species; bool warmblooded; // direct derived class of Animal class Cat : public Animal { string range[100]; float favoriteprey[100][100]; // direct derived class of Cat // indirect derived class of Animal class HouseCat : public Cat { string toys[10000]; string catdoctor; string apparentowner; direct base class for Cat direct base class for HouseCat indirect base class for HouseCat Animal Cat HouseCat directly derived from directly derived from indirectly derived from 15

Protected Members In addition to public and private members, C++ provides protected members Without inheritance, a protected member is just like a private member I.e., only visible within the same class In public inheritance, a protected member of a base class is also protected in its derived classes I.e., also visible in the derived classes Consequently, methods of directly or indirectly derived classes can access protected members from their base classes Note that a friend function of a class can access both private and protected members of the class (refer to chap. 6) 16

Example of protected Members // base class class BC { void set_x(int a) { x = a; } protected: int get_x() { return x; } int x; class DC : public BC { void add2() { x += 2; // ERROR: x is // private in BC int main() { DC d; d.set_x(3); // OK: set_x is public in DC cout << d.get_x() << '\n'; // ERROR: get_x is protected in DC d.add2(); // OK: add2 is public in DC } Member Access status in class DC Access status in main function } int c = get_x(); // OK set_x(c + 2); set_x get_x x add2 public protected Not accessible public Accessible Not accessible Not accessible Accessible 17

Example of protected Members (cont.) BC x BC x set_x get_x X set_x get_x X DC DC add2 set_x add2 get_x : public : protected : private : inherited main X X 18

Protected Members of Objects A derived class can access protected members inherited from a base class, but can NOT access protected members of objects even though they belong to the base class class BC { protected: int get_w() const; class DC : public BC { void get_val() const { return get_w(); } void base_w() const { BC b; cout << b.get_w() << '\n'; // ERROR: b.get_w is not // visible in DC since // it is a member of // a BC object, not one // inherited to DC } 19

Better Class Design for Protected Data Members In general, protected data members should be avoided in strict terms of information hiding They can usually be made private and accessible by protected accessor methods Exceptively, some complex data members would be declared protected instead of providing complicated accessor methods E.g., a multi-dimensional array of complicated structures class BC { protected: int y; class BC { protected: int get_y() const { return y; } void set_y(int a) { y = a; } int y; 20

Constructors under Inheritance A derived class is a specialized version of a base class Basically, an object of a derived class contains members from the base class It also contains members that are specific to derived class itself Thus, a base class constructor also needs to be invoked when a derived class object is created The base class constructor handles initialization and other matters for the from the base class part of the object And the derived class constructor handles the added by derived class part of the object initializes [ An object of a derived class ] Parts from the base class Base Class Constructors Parts added by the derived class initializes Derived Class Constructors 21

Example of Derived Class Constructor Invocation class Animal { Animal() { species = "Animal"; } Animal(const char* s) { species = s; } string species; class Primate : public Animal { Primate() : Animal("Primate ) {} Primate(int n) : Animal("Primate ) { heart_cham = n; } int heart_cham; In the initialization section, this indicates to invoke Animal constructor before executing its body Animal slug; // Animal() only Animal tweety("canary ); // Animal(const char*) only Primate godzilla; // Animal( Primate ) Primate() Primate human(4); // Animal( Primate ) Primate(int) // : note base class constructors are // invoked first 22

Two Basic Rules for Constructors under Inheritance [Rule #1] If no constructor is defined explicitly The system provides the default constructor [Rule #2] If no specific constructor of the base class is invoked in the derived class The default constructor of the base class is automatically invoked whenever a derived class object is created 23

Application of the Basic Rules When a DC Object is Created Base Class Derived Class No constructor is defined explicitly (system provides default constructor) At least one constructor is defined (system does NOT provide default constructor for DC) No constructor is defined explicitly (system provides default constructor) 1 The system-provided default constructors of BC and DC are invoked automatically 2 The system-provided default constructor of BC and appropriate DC constructors are invoked At least one constructor is defined (system does NOT provide default constructor for BC) 3 Programmer MUST provide the default constructor for BC (which is automatically invoked by the system provided DC constructor) 4 Appropriate BC and DC constructors are invoked 24

Constructor Example (1) class BC { // base class BC() { x = y = -1; } // default constructor protected: int get_x() const { return x; } int get_y() const { return y; } int x; int y; class DC : public BC { // derived class has no constructor // -> system provides DC() void write() const { cout << get_x()*get_y() << '\n'; } int main() { DC d1; d1.write(); } // BC() DC() is invoked automatically // 1 is written to the standard output 25

Constructor Example (2) // BC has constructors, but // no default constructor class BC { BC(int a) { x = a, y = 999; } BC(int a1, int a2) { x = a1; y = a2; } int x; int y; // DC has a constructor class DC : public BC { DC(int n) { z = n; } // *** ERROR: no BC() int z; // Solution 2: add default // constructor to BC class BC { BC() { } BC(int a) { x = a, y = 999; } // Solution 1: explicitly // invoke BC constructor class DC : public BC { DC(int n) : BC(10) { z = n; } 26

Constructor Example (3) class BC { BC() { cout << BC() executed \n ; } int x; class DC : public BC { DC() : BC() { cout << DC() executed \n ; } // legal but unnecessary int y; BC() executes int main() { DC() executes DC d; } 27

Constructor Example (4) class Animal { Animal(const char* s) { species = s; } string species; class Primate : public Animal { Primate() : Animal( Primate ) { } int heart_cham; class Human : public Primate { Human() : Primate() { } Human jill(); Human fred(); [ Execution Sequence ] Base Class Derived Class Animal::Animal(char *) Primate::Primate() Human::Human() 28

Constructor Example (5) class Team { // base class Team(int len = 100) { names = new string[maxno = len]; } // dynamically allocates storage for a pointer member protected: string* names; int maxno; class BaseballTeam : public Team { // derived class // make sure to invoke BC constructor Team(int) // to allocate storage for names before using it BaseballTeam(const string s[], int si) : Team(si) { for (int i = 0; i < si; i++) names[i] = s[i]; } 29

Destructors under Inheritance Constructors in an inheritance hierarchy are invoked in a base class to derived class order On the other hand, destructors in an inheritance hierarchy are invoked in the reverse order, i.e., a derived class to base class order This ensures that the most recently initialized part of an object is the first to be finalized (i.e., the most recently allocated storage is freed first) Note a destructor NEVER explicitly invokes another destructor, since each class has at most one destructor 30

Destructor Example class BC { BC() { cout << "BC's constructor\n"; } ~BC() { cout << "BC's destructor\n"; } class DC : public BC { DC() : BC() { cout << "DC's constructor\n"; } ~DC() { cout << "DC's destructor\n"; } int main() { DC d; return 0; } BC's constructor DC's constructor DC's destructor BC's destructor 31

Multiple Inheritance With multiple inheritance, a derived class may have two or more base classes With only single inheritances, an inheritance hierarchy forms a tree, with multiple inheritances it may form a graph ( pp.36) Meanings of inheritance In a single inheritance hierarchy, a derived class typically represents a specialized version of its base class In a multiple inheritance hierarchy, a derived class may represents a combination of its multiple base classes BC DC Single inheritance BC1 DC BC2 Multiple inheritance For reference, Java does NOT allow multiple inheritance for classes (c.f., only allows interfaces to inherit from multiple interfaces) 32

Multiple Inheritance Example (1) // Popup menu class no scroll bars class PopupMenu { int menuchoices; Win* menusubwins; // Scrolled window class not a popup class ScrollWin : public Window { Widget horizontalsb; Widget verticalsb; Window PopupMenu ScrollWin ScrollPopupMenu // Multiple inheritance: combination of popup & scroll bars class ScrollPopupMenu : public PopupMenu, public ScrollWin { 33

Multiple Inheritance and Access to Members The basic rules of inheritance and access in single inheritance are intactly applied to multiple inheritance A derived class inherits data members and methods from all its base classes In consequence, multiple inheritance increases opportunity for name conflict (e.g., name hiding) Because the conflict can occur not only between the derived class and its multiple base classes but between the base classes It is up to the programmer to prevent or resolve this kind of name conflicts 34

Multiple Inheritance Example (2) class BC1 { // base class 1 void set_x(float a) { x = a } void tester() { DC d1; // DC::set_x d1.set_x(137); class BC2 { // base class 2 void set_x(char a) { x = a } class DC // derived class : public BC1, public BC2 { void set_x(int a) { x = a } // Error: DC::set_x hides // set_x of BC1 and BC2 d1.set_x(1.23); d1.set_x( c ); // BC1::set_x d1.bc1::set_x(1.23); // BC2::set_x d1.bc2::set_x( c ); 35

Multiple Inheritance Originated from the Same Class Multiple inheritance hierarchy may be complicated This may lead to the situation in which a derived class inherits multiple times from the same indirect base class It is wasteful and confusing class BC { int x; // indirect base class of DC3 class DC1 : public BC { // inheritance path 1 class DC2 : public BC { // inheritance path 2 class DC3 : public DC1, public DC2 { // x comes twice in class DC3 int x DC1 int x int x BC DC3 int x int x DC2 36

Virtual Base Classes The previous problem can be solved by declaring DC1 and DC2 as virtual base classes for DC3 This tells DC1 and DC2 to send only one copy of whatever they inherit from there common ancestor BC to DC3 class BC { int x; class DC1 : virtual public BC { class DC2 : virtual public BC { class DC3 : public DC1, public DC2 { // x comes once to DC3 37