Inheritance and Polymorphism

Similar documents
Software Design Abstract Data Types

Namespaces and Class Hierarchies

Unified Modeling Language a case study

Practice Problems CS2620 Advanced Programming, Spring 2003

Lab 2: ADT Design & Implementation

IS 0020 Program Design and Software Tools

Review: C++ Basic Concepts. Dr. Yingwu Zhu

SRM ARTS AND SCIENCE COLLEGE SRM NAGAR, KATTANKULATHUR

PIC10B/1 Winter 2014 Exam I Study Guide

Computer Programming with C++ (21)

Operator Overloading

Inheritance, and Polymorphism.

Time(int h, int m, int s) { hrs = h; mins = m; secs = s; } void set(int h, int m, int s) { hrs = h; mins = m; secs = s; }

CS 1337 Computer Science II Page 1

More About Classes. Gaddis Ch. 14, CS 2308 :: Fall 2015 Molly O'Neil

Unit Testing. Contents. Steven Zeil. July 22, Types of Testing 2. 2 Unit Testing Scaffolding Drivers Stubs...

Operator Overloading in C++ Systems Programming

Unit Testing. Steven Zeil. July 22, Types of Testing 2. 2 Unit Testing Scaffolding Drivers Stubs...

Classes: A Deeper Look, Part 2

Financial computing with C++

EECE.3220: Data Structures Spring 2017

COP4530 Data Structures, Algorithms and Generic Programming Recitation 4 Date: September 14/18-, 2008

CAAM 420 Fall 2012 Lecture 29. Duncan Eddy

Templates and Vectors

Object oriented programming

Welcome to MCS 360. content expectations. using g++ input and output streams the namespace std. Euclid s algorithm the while and do-while statements

Abstract Data Types (ADT) and C++ Classes

Modern C++ for Computer Vision and Image Processing. Igor Bogoslavskyi

CPSC 427: Object-Oriented Programming

Lecture 7. Log into Linux New documents posted to course webpage

1 // Fig. 6.13: time2.cpp 2 // Member-function definitions for class Time. 3 #include <iostream> Outline. 4 5 using std::cout; 6 7 #include <iomanip>

Intermediate Programming, Spring 2017*

Due Date: See Blackboard

Object-Oriented Design (OOD) and C++

CPSC 427: Object-Oriented Programming

EINDHOVEN UNIVERSITY OF TECHNOLOGY Department of Mathematics and Computer Science

Programming, numerics and optimization

pointers & references

Polymorphism Part 1 1

Object Oriented Programming. Solved MCQs - Part 2

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

selectors, methodsinsert() andto_string() the depth of a tree and a membership function

this Pointer, Constant Functions, Static Data Members, and Static Member Functions this Pointer (11.1) Example of this pointer

Operator overloading

CE221 Programming in C++ Part 1 Introduction

Shahram Rahatlou. Computing Methods in Physics. Overloading Operators friend functions static data and methods

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

Short Notes of CS201

CSCE 110 PROGRAMMING FUNDAMENTALS

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

Due Date: See Blackboard

Stack Applications. parsing a postfix expression evaluating postfix expressions. converting infix sums from infix to postfix

Passing arguments to functions by. const member functions const arguments to a function. Function overloading and overriding Templates

CS201 - Introduction to Programming Glossary By

CSI33 Data Structures

Homework 5. Yuji Shimojo CMSC 330. Instructor: Prof. Reginald Y. Haseltine

Iterators. node UML diagram implementing a double linked list the need for a deep copy. nested classes for iterator function objects

Chapter 18 - C++ Operator Overloading

Where do we stand on inheritance?

Programming Abstractions

Distributed Real-Time Control Systems. Lecture 17 C++ Programming Intro to C++ Objects and Classes

Expression Trees and the Heap

Use the dot operator to access a member of a specific object.

Copying Data. Contents. Steven J. Zeil. November 13, Destructors 2

Lists. linking nodes. constructors. chasing pointers. MCS 360 Lecture 11 Introduction to Data Structures Jan Verschelde, 17 September 2010.

CSS 342 Data Structures, Algorithms, and Discrete Mathematics I. Lecture 2. Yusuf Pisan

University of Swaziland Department OfComputer Science Main Examination December 2016

Hashing. mapping data to tables hashing integers and strings. aclasshash_table inserting and locating strings. inserting and locating strings

A Deeper Look at Classes

CPSC 427: Object-Oriented Programming

C++ Constructs by Examples

COMS W3101 Programming Language: C++ (Fall 2016) Ramana Isukapalli

AN OVERVIEW OF C++ 1

END TERM EXAMINATION

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

Due Date: See Blackboard

C++ PROGRAMMING LANGUAGE: DYNAMIC MEMORY ALLOCATION AND EXCEPTION IN C++. CAAM 519, CHAPTER 15

Comp151. Inheritance: Initialization & Substitution Principle

การทดลองท 8_2 Editor Buffer Array Implementation

Absolute C++ Walter Savitch

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

Starting Savitch Chapter 10. A class is a data type whose variables are objects. Some pre-defined classes in C++ include int,

W3101: Programming Languages C++ Ramana Isukapalli

CSCI 123 Introduction to Programming Concepts in C++

Comp151. Generic Programming: Container Classes

Financial computing with C++

Scott Gibson. Pointers & Dynamic Memory. Pre & Co Requisites. Random Access Memory. Data Types. Atomic Type Sizes

B-Trees. nodes with many children a type node a class for B-trees. an elaborate example the insertion algorithm removing elements

1. Match each of the following data types with literal constants of that data type. A data type can be used more than once. A.

Paytm Programming Sample paper: 1) A copy constructor is called. a. when an object is returned by value

I BSc(IT) [ Batch] Semester II Core: Object Oriented Programming With C plus plus - 212A Multiple Choice Questions.

Software Design and Analysis for Engineers

CS304 Object Oriented Programming Final Term

Object oriented programming

Hashing. inserting and locating strings. MCS 360 Lecture 28 Introduction to Data Structures Jan Verschelde, 27 October 2010.

EL2310 Scientific Programming

Chapter 1: Object-Oriented Programming Using C++

CSE 333. Lecture 9 - intro to C++ Hal Perkins Department of Computer Science & Engineering University of Washington

CS250 Final Review Questions

Lecture 8. Xiaoguang Wang. February 13th, 2014 STAT 598W. (STAT 598W) Lecture 8 1 / 47

Transcription:

Inheritance and Polymorphism 1 Inheritance extending a clock to an alarm clock deriving a class 2 Polymorphism virtual functions and polymorphism abstract classes MCS 360 Lecture 8 Introduction to Data Structures Jan Verschelde, 15 September 2017 Introduction to Data Structures (MCS 360) Inheritance and Polymorphism L-8 15 September 2017 1 / 25

Inheritance and Polymorphism 1 Inheritance extending a clock to an alarm clock deriving a class 2 Polymorphism virtual functions and polymorphism abstract classes Introduction to Data Structures (MCS 360) Inheritance and Polymorphism L-8 15 September 2017 2 / 25

an alarm clock Recall our class Clock as an encapsulation of some of the functionality of ctime. #include "clock.h" #include <iostream> using namespace std; int main() { Clock c; cout << "The current time is " << c << "." << endl; } return 0; Introduction to Data Structures (MCS 360) Inheritance and Polymorphism L-8 15 September 2017 3 / 25

the file clock.h #ifndef CLOCK_H #define CLOCK_H #include <ostream> #include <string> class Clock { public: Clock(); int get_hours() const; int get_minutes() const; int get_seconds() const; friend std::ostream& operator<< (std::ostream& os, const Clock& c); bool operator==(const Clock& c) const; Introduction to Data Structures (MCS 360) Inheritance and Polymorphism L-8 15 September 2017 4 / 25

clock.h continued private: }; int hours; /* hours in 24 hour format integer in the range 0..23 */ int minutes; /* minutes in range 0..59 */ int seconds; /* integers in range 0..61 allowing for leap second */ #endif Introduction to Data Structures (MCS 360) Inheritance and Polymorphism L-8 15 September 2017 5 / 25

modeling an alarm clock An alarm clock is 1 a clock with the current time; 2 the fixed time of the alarm. We reuse the existing code: 1 extend the definition of clock; 2 keep the class Clock. The class Alarm_Clock inherits from Clock: 1 Clock is the base class. 2 Alarm_Clock is a derived class. Introduction to Data Structures (MCS 360) Inheritance and Polymorphism L-8 15 September 2017 6 / 25

Inheritance and Polymorphism 1 Inheritance extending a clock to an alarm clock deriving a class 2 Polymorphism virtual functions and polymorphism abstract classes Introduction to Data Structures (MCS 360) Inheritance and Polymorphism L-8 15 September 2017 7 / 25

deriving a class the alarm_clock.h file #ifndef ALARM_CLOCK_H #define ALARM_CLOCK_H #include "clock.h" #include <ostream> #include <string> class Alarm_Clock : public Clock { Alarm_Clock is derived from Clock. If public is omitted, then the members of Clock are not visible to clients of Alarm_Clock. Introduction to Data Structures (MCS 360) Inheritance and Polymorphism L-8 15 September 2017 8 / 25

the constructor class Alarm_Clock : public Clock { public: Alarm_Clock(int h, int m, int s) : Clock(), hours(h), minutes(m), seconds(s) {} /* sets the alarm clock to the time h:m:s */ The constructor of the class Clock is called and the arguments of Alarm_Clock are copied to the data attributes hours, minutes, and seconds. Introduction to Data Structures (MCS 360) Inheritance and Polymorphism L-8 15 September 2017 9 / 25

data and functions int get_alarm_hours() const; int get_alarm_minutes() const; int get_alarm_seconds() const; private: }; #endif int hours; /* hours in 24 hour format integer in the range 0..23 */ int minutes; /* minutes in range 0..59 */ int seconds; /* integers in range 0..61 allowing for leap second */ An object of the class Alarm_Clock stores two triplets of integers. Introduction to Data Structures (MCS 360) Inheritance and Polymorphism L-8 15 September 2017 10 / 25

Unified Modeling Language Clock - hours - minutes - seconds + get_hours() + get_minutes() + get_seconds() + << + == Alarm_Clock - hours - minutes - seconds + get_alarm_hours() + get_alarm_minutes() + get_alarm_seconds() Introduction to Data Structures (MCS 360) Inheritance and Polymorphism L-8 15 September 2017 11 / 25

Visibility Rules Because of the class Alarm_Clock : public Clock all clients of Alarm_Clock have access to the public members of Clock. The data hours, minutes, seconds are private and therefore only accessible via the respective get_hours(), get_minutes(), get_seconds(). To make members of a class also available to derived classes, replace private by protected. Introduction to Data Structures (MCS 360) Inheritance and Polymorphism L-8 15 September 2017 12 / 25

testing Alarm_Clock #include "clock.h" #include "alarm_clock.h" #include <iostream> using namespace std; int main() { Clock c; cout << "The current time is " << c << "." << endl; Alarm_Clock a(21,11,8); On a, we can apply public methods of Clock. Introduction to Data Structures (MCS 360) Inheritance and Polymorphism L-8 15 September 2017 13 / 25

Inheritance and Polymorphism 1 Inheritance extending a clock to an alarm clock deriving a class 2 Polymorphism virtual functions and polymorphism abstract classes Introduction to Data Structures (MCS 360) Inheritance and Polymorphism L-8 15 September 2017 14 / 25

virtual functions Adding an operation to clock.h: virtual std::string to_string() const; /* returns a string representation of a clock */ In clock.cpp: std::string Clock::to_string() const { using std::ostringstream; ostringstream s; s << std::setfill( 0 ) << std::setw(2) << hours << ":" << std::setw(2) << minutes << ":" << std::setw(2) << seconds; return s.str(); } Introduction to Data Structures (MCS 360) Inheritance and Polymorphism L-8 15 September 2017 15 / 25

extending << Using to_string shortens the definition of <<. In clock.cpp: std::ostream& operator<< (std::ostream& os, const Clock& c) { os << c.to_string(); } return os; Because to_string() is virtual in Clock, we can provide another definition in a derived class. An derived class inherits <<. In <<, the proper definition of to_string() is called, depending on the operand of <<. Introduction to Data Structures (MCS 360) Inheritance and Polymorphism L-8 15 September 2017 16 / 25

overriding functions Also in Alarm_Clock we have to_string(): std::string Alarm_Clock::to_string() const { using std::ostringstream; ostringstream s; s << std::setfill( 0 ) << std::setw(2) << hours << ":" << std::setw(2) << minutes << ":" << std::setw(2) << seconds << " set at " << Clock::to_string(); return s.str(); } We use to_string() of Clock() when we define to_string() of Alarm_Clock(). Introduction to Data Structures (MCS 360) Inheritance and Polymorphism L-8 15 September 2017 17 / 25

testing continued int main() { Clock c; cout << "The current time is " << c << "." << endl; Alarm_Clock a(21,11,8); cout << "The alarm is " << a << "." << endl; Note that << is defined only once! Introduction to Data Structures (MCS 360) Inheritance and Polymorphism L-8 15 September 2017 18 / 25

more polymorphism We first define a pointer to the base class: Clock *d; d = new Alarm_Clock(12,50,0); cout << "to_string on Clock : " << d->clock::to_string() << endl; cout << "to_string on Alarm_Clock : " << d->to_string() << endl; The pointer d refers to an alarm clock after the new. Different definitions of to_string() apply. Introduction to Data Structures (MCS 360) Inheritance and Polymorphism L-8 15 September 2017 19 / 25

a virtual destructor A last addition to clock.h: virtual ~Clock() {} /* needed for delete in derived classes */ The code defined in the destructor is executed when the delete method is called. The delete deallocates memory allocated for objects declared as pointers and constructed via new. Introduction to Data Structures (MCS 360) Inheritance and Polymorphism L-8 15 September 2017 20 / 25

the makefile gpp=/usr/bin/g++ test_clock: $(gpp) -c clock.cpp $(gpp) -c test_clock.cpp $(gpp) -o /tmp/test_clock clock.o \ test_clock.o test_alarm_clock: $(gpp) -c clock.cpp $(gpp) -c alarm_clock.cpp $(gpp) -c test_alarm_clock.cpp $(gpp) -o /tmp/test_alarm_clock clock.o \ alarm_clock.o test_alarm_clock.o Introduction to Data Structures (MCS 360) Inheritance and Polymorphism L-8 15 September 2017 21 / 25

Inheritance and Polymorphism 1 Inheritance extending a clock to an alarm clock deriving a class 2 Polymorphism virtual functions and polymorphism abstract classes Introduction to Data Structures (MCS 360) Inheritance and Polymorphism L-8 15 September 2017 22 / 25

abstract classes Every food has an amount of calories: the data attribute is a double, kept private, a public function returns it value. Substances that provide energy in food are carbohydrates, proteins, and fats. Of interest is a function to return the percentage of these substances in a food object. The cont = 0 at the end of virtual double pct_fact() const = 0; must be there for a pure virtual function in an abstract class. Introduction to Data Structures (MCS 360) Inheritance and Polymorphism L-8 15 September 2017 23 / 25

defining an abstract class #ifndef FOOD_H #define FOOD_H class Food { private: double calories; public: double get_calories() const { return calories; } virtual double pct_carbohydrates() const = 0; virtual double pct_protein() const = 0; virtual double pct_fat() const = 0; }; #endif Introduction to Data Structures (MCS 360) Inheritance and Polymorphism L-8 15 September 2017 24 / 25

Summary + Exercises Started Chapter 3: Inheritance and Class Hierarchies. Exercises: 1 Define a class Bank_Account to hold the balance of a bank account. The balance is a private float. The initial balance is given to the constructor. Write public functions to withdraw and deposit. A to_string() method returns a string to format the balance with 2 places after the decimal point. Use to_string() in <<. Test the class with a small program. 2 Derive from Bank_Account aclasssavings_account. An extra data attribute is the interest rate, set at the creation of the account. Write a function to update the balance with the yield from the interest. Override the to_string() method to display the interest rate along with the balance. Show that by the virtual to_string() in Bank_Account, there is no need to define << for a savings account. Introduction to Data Structures (MCS 360) Inheritance and Polymorphism L-8 15 September 2017 25 / 25