CSE 303 Lecture 23. Inheritance in C++ slides created by Marty Stepp

Similar documents
C++ Inheritance I. CSE 333 Spring Instructor: Justin Hsia

Inheritance, and Polymorphism.

CSE 333 Lecture 15 - inheritance

C++ Inheritance I. CSE 333 Autumn 2018

CSE 333 Lecture 15 - inheritance

CSE 303: Concepts and Tools for Software Development

CS11 Introduction to C++ Fall Lecture 7

Polymorphism Part 1 1

Inheritance. Benefits of Java s Inheritance. 1. Reusability of code 2. Code Sharing 3. Consistency in using an interface. Classes

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

VIRTUAL FUNCTIONS Chapter 10

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

CS-202 Introduction to Object Oriented Programming

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

Chapter 1: Object-Oriented Programming Using C++

C++ For Science and Engineering Lecture 27

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

Lecture 18 CSE11 Fall 2013 Inheritance

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

CSE 374 Programming Concepts & Tools. Hal Perkins Fall 2015 Lecture 19 Introduction to C++

Inheritance and Polymorphism

Lab 2: ADT Design & Implementation

Practice for Chapter 11

Computer Programming Inheritance 10 th Lecture

ECE 3574: Dynamic Polymorphism using Inheritance

Lecture 5: Inheritance

CS250 Final Review Questions

Relationships Between Real Things. CSE 143 Java. Common Relationship Patterns. Composition: "has a" CSE143 Sp Student.

Java Object Oriented Design. CSC207 Fall 2014

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

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010

G52CPP C++ Programming Lecture 13

GEA 2017, Week 4. February 21, 2017

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

Inheritance -- Introduction

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

Midterm Review. PIC 10B Spring 2018

Object-Oriented Programming (OOP) Fundamental Principles of OOP

IT101. Inheritance, Encapsulation, Polymorphism and Constructors

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

Binghamton University. CS-140 Fall Dynamic Types

C++ Inheritance II, Casting

CS32 - Week 4. Umut Oztok. Jul 15, Umut Oztok CS32 - Week 4

Topic 31 - inheritance

Admin. CS 112 Introduction to Programming. Recap: OOP Analysis. Software Design and Reuse. Recap: OOP Analysis. Inheritance

Chapter 14 Abstract Classes and Interfaces

Lecture Contents CS313D: ADVANCED PROGRAMMING LANGUAGE. What is Inheritance?

Inheritance and Encapsulation. Amit Gupta

Lecture-5. Miscellaneous topics Templates. W3101: Programming Languages C++ Ramana Isukapalli

OVERRIDING. 7/11/2015 Budditha Hettige 82

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

Object Oriented Design

Chapter 12. OOP: Creating Object-Oriented Programs The McGraw-Hill Companies, Inc. All rights reserved. McGraw-Hill

Programming II (CS300)

CS313D: ADVANCED PROGRAMMING LANGUAGE

Inheritance and Polymorphism

CMSC 132: Object-Oriented Programming II

Chapter 15: Inheritance, Polymorphism, and Virtual Functions

Arrays Classes & Methods, Inheritance

Programming Abstractions

Polymorphism 2/12/2018. Which statement is correct about overriding private methods in the super class?

This examination has 11 pages. Check that you have a complete paper.

CE221 Programming in C++ Part 1 Introduction

What property of a C# array indicates its allocated size? What keyword in the base class allows a method to be polymorphic?

Polymorphism CSCI 201 Principles of Software Development

Introducing C++ to Java Programmers

Object Oriented Programming. Java-Lecture 11 Polymorphism

Ministry of Higher Education Colleges of Applied Sciences Final Exam Academic Year 2009/2010. Student s Name

Relationships Between Real Things CSE 143. Common Relationship Patterns. Employee. Supervisor

Object Oriented Programming: Inheritance Polymorphism

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

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

Chapter 5 Object-Oriented Programming

CS 251 Intermediate Programming Inheritance

Comp 249 Programming Methodology

Comp151. Inheritance: Initialization & Substitution Principle

Inheritance and object compatibility

CS 106X Lecture 26: Inheritance and Polymorphism in C++

INHERITANCE & POLYMORPHISM. INTRODUCTION IB DP Computer science Standard Level ICS3U. INTRODUCTION IB DP Computer science Standard Level ICS3U

CIS 110: Introduction to computer programming

Chapter 7. Inheritance

PROGRAMMING LANGUAGE 2

Data Abstraction. Hwansoo Han

Inheritance (IS A Relationship)

Java and OOP. Part 3 Extending classes. OOP in Java : W. Milner 2005 : Slide 1

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

Data Structures and Other Objects Using C++

Intermediate Programming, Spring 2017*

CS111: PROGRAMMING LANGUAGE II

And Even More and More C++ Fundamentals of Computer Science

Relationships Between Real Things CSC 143. Common Relationship Patterns. Composition: "has a" CSC Employee. Supervisor

ECE 122. Engineering Problem Solving with Java

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

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

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

Building Java Programs

Object Oriented Programming. Solved MCQs - Part 2

AP CS Unit 6: Inheritance Notes

The software crisis. code reuse: The practice of writing program code once and using it in many contexts.

Friend Functions, Inheritance

Transcription:

CSE 303 Lecture 23 Inheritance in C++ slides created by Marty Stepp http://www.cs.washington.edu/303/ 1

Case study exercise Represent a portfolio of a person's financial investments. Every asset has a cost(how much was paid for it) and a market value (how much it is currently worth). The difference between these is the profit. Different assets compute their market value in different ways. Types of assets can be in a portfolio: A Stockhas a symbol (such as "MSFT" for Microsoft), a number of shares, the total cost paid, and a current price per share. A Dividend Stockis a stock that also gives back dividendpayments. Cashis simply an amount of money. It never incurs profit or loss. 2

A possible design A class represents each type of asset. Problem: Redundancy. Problem: Cannot treat multiple investment types the same way (such as putting them into a portfolio array). 3

Inheritance inheritance: A parent-child relationship between classes. a child (derived class) extends a parent (base class) benefits of inheritance: code reuse: inherit code from superclass polymorphism: Ability to redefine existing behaviors, so that when a client makes calls on different objects, it can have different results. 4

A better design (Java) an interface represents the top-level supertype (no code sharing) inheritance and subclassing gives us code sharing (DividendStock) 5

Access specifiers directory public private protected description visible to all other classes visible only to the current class (even subclasses cannot directly access it) visible to current class and its subclasses declare a member as protectedif: you don't want random clients accessing them, but you expect to be subclassed, and you don't mind for your subclasses to have access to it 6

Public inheritance #include "BaseClass.h" class Name : public BaseClass {... ; inherits all behavior from the given base class (derived class must include base class's.h file) the following are not inherited: constructors and destructors the assignment operator =(if it was overridden) 7

DividendStock.h #ifndef _DIVIDENDSTOCK_H #define _DIVIDENDSTOCK_H #include <string> #include "Stock.h" using namespace std; // Represents a stock purchase that also pays dividends. class DividendStock : public Stock { private: double m_dividends; // amount of dividends paid ; #endif public: DividendStock(string symbol, double shareprice = 0.0); double dividends() const; double marketvalue() const; void paydividend(double amountpershare); 8

Inheritance and constructors ClassName::ClassName(params) : BaseClassName(params) { statements; Constructors are not inherited but every time a subclass object is constructed, a constructor from the base class must be called (to initialize that part of the object) by default, calls the base's () constructor (if one exists) 9

DividendStock.cpp #include "DividendStock.h" // Constructs a new stock with the given symbol and no shares. DividendStock::DividendStock(string symbol, double shareprice) : Stock(symbol, shareprice) { m_dividends = 0.0; // Returns this DividendStock's market value, which is // a normal stock's market value plus any dividends. double DividendStock::marketValue() const { return shares() * shareprice() + dividends(); // Returns the total amount of dividends paid on this stock. double DividendStock::dividends() const { return m_dividends; // Records a dividend of the given amount per share. void DividendStock::payDividend(double amountpershare) { m_dividends += amountpershare * shares(); 10

A problem Client program's old output: value: $1234.56 cost: $1234.56 profit: $ 0.00 value: $ 475.00 cost: $ 500.00 profit: $ -25.00 value: $3500.00 cost: $2000.00 profit: $1500.00 Client program's new output: value: $1234.56 cost: $1234.56 profit: $ 0.00 value: $ 475.00 cost: $ 500.00 profit: $ -25.00 value: $3500.00 cost: $2000.00 profit: $1000.00 What happened? 11

Method dispatching static dispatch: Method calls are looked up at compile-time. dynamic (virtual) dispatch: Method calls looked up at runtime. // Stock.cpp double Stock::profit() const { // Stock's version of marketvalue / cost is used return marketvalue() - cost(); In Java, all objects' methods use dynamic dispatch automatically. In C++, methods use static dispatch by default. If you override a method, superclass code won't notice the change. (This is considered a mistake in the design of C++.) 12

Virtual methods // Stock.h class Stock {... public: virtual double marketvalue() const;... ; If you want a method/operator to use dynamic dispatch, put the keyword virtualin its header (in the.h, not.cpp). Rule of thumb: Make all methods virtual if you expect subclassing. Destructors should also be virtual to avoid complex leak cases. 13

Virtual dispatch example class A { public: void m1() { cout << "a1" << endl; virtual void m2() { cout << "a2" << endl; ; class B : public A { public: void m1() { cout << "b1" << endl; virtual void m2() { cout << "b2" << endl; ; int main() { A* var1 = new B(); var1->m1(); // a1 var1->m2(); // b2 B* var2 = new B(); var2->m1(); // b1 var2->m2(); // b2 14

Override with redundancy // Stock.cpp double Stock::marketValue() const { return shares() * shareprice(); // DividendStock.cpp double DividendStock::marketValue() const { return shares() * shareprice() + dividends(); DividendStock's value is really the old value plus the dividends We'd like the code to reflect that relationship. 15

Calling a base class method BaseClassName::methodName(parameters) // DividendStock.cpp double DividendStock::marketValue() const { return Stock::marketValue() + dividends(); analogous to super.methodname() in Java 16

Virtual destructors class B : public A {... B* b = new B(); A* a = b; delete a; Will the B::~B() destructor get called? Only if A::~A() was declared virtual. In what order will the destructors be called? ~B(), then ~A(). Rule of thumb: Declare all destructors virtual. 17