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

Similar documents
C++ Inheritance I. CSE 333 Autumn 2018

C++ Inheritance II, Casting

CSE 333 Lecture 15 - inheritance

CSE 333 Lecture 15 - inheritance

C++ Constructor Insanity

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

Server-side Programming

Concurrency and Threads

C++ Inheritance II, Casting

Memory and Arrays. CSE 333 Spring Instructor: Justin Hsia

Announcements. CSCI 334: Principles of Programming Languages. Lecture 18: C/C++ Announcements. Announcements. Instructor: Dan Barowy

Java and C I. CSE 351 Spring Instructor: Ruth Anderson

Java and C. CSE 351 Autumn 2018

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

IP Addresses, DNS. CSE 333 Spring Instructor: Justin Hsia

Polymorphism Part 1 1

Project. C++: Inheritance III. Plan. Project. Before we begin. The final exam. Advanced Topics. Project. This week in the home stretch

Java and C CSE 351 Spring

04-24/26 Discussion Notes

C++ Important Questions with Answers

QUIZ. Write the following for the class Bar: Default constructor Constructor Copy-constructor Overloaded assignment oper. Is a destructor needed?

The Heap and Structs. CSE 333 Spring Instructor: Justin Hsia

Object-Oriented Programming, Iouliia Skliarova

Overriding Variables: Shadowing

CS 251 Intermediate Programming Inheritance

Data Abstraction. Hwansoo Han

Lecture 15a Persistent Memory & Shared Pointers

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

CS11 Introduction to C++ Fall Lecture 7

Announcements. Lecture 05a Header Classes. Midterm Format. Midterm Questions. More Midterm Stuff 9/19/17. Memory Management Strategy #0 (Review)

G52CPP C++ Programming Lecture 13

Chapter 15: Inheritance, Polymorphism, and Virtual Functions

QUIZ. How could we disable the automatic creation of copyconstructors

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

G52CPP C++ Programming Lecture 10. Dr Jason Atkin

CS153: Compilers Lecture 11: Compiling Objects

(12-1) OOP: Polymorphism in C++ D & D Chapter 12. Instructor - Andrew S. O Fallon CptS 122 (April 3, 2019) Washington State University

Programming Exercise 14: Inheritance and Polymorphism

VIRTUAL FUNCTIONS Chapter 10

G52CPP C++ Programming Lecture 9

MARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Midterm #2 Examination 12:30 noon, Thursday, March 15, 2012

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

Week 7. Statically-typed OO languages: C++ Closer look at subtyping

CSE 303: Concepts and Tools for Software Development

Inheritance and Interfaces

CSE 333 Lecture C++ final details, networks

ECE 3574: Dynamic Polymorphism using Inheritance

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

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

Java Object Oriented Design. CSC207 Fall 2014

Spring 2003 Instructor: Dr. Shahadat Hossain. Administrative Matters Course Information Introduction to Programming Techniques

G Programming Languages - Fall 2012

Final C Details, Build Tools

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

University of British Columbia CPSC 111, Intro to Computation Jan-Apr 2006 Tamara Munzner

G52CPP C++ Programming Lecture 12

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

CE221 Programming in C++ Part 1 Introduction

G Programming Languages Spring 2010 Lecture 9. Robert Grimm, New York University

What are the characteristics of Object Oriented programming language?

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010

CIS 190: C/C++ Programming. Lecture 11 Polymorphism

Announcements. Lecture 04b Header Classes. Review (again) Comments on PA1 & PA2. Warning about Arrays. Arrays 9/15/17

Intro to C: Pointers and Arrays

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

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

Inheritance, and Polymorphism.

Review: C Strings. A string in C is just an array of characters. Lecture #4 C Strings, Arrays, & Malloc

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

Common Misunderstandings from Exam 1 Material

Caches II. CSE 351 Autumn Instructor: Justin Hsia

Lecture 18 CSE11 Fall 2013 Inheritance

CSE 333 Lecture 2 - arrays, memory, pointers

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

Media Computation. Lecture 16.1, December 8, 2008 Steve Harrison

Memory, Data, & Addressing II

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

QUIZ. How could we disable the automatic creation of copyconstructors

CS-202 Introduction to Object Oriented Programming

CSE 401/M501 Compilers

Implementing Higher-Level Languages. Quick tour of programming language implementation techniques. From the Java level to the C level.

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

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

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

Memory, Data, & Addressing I

CSE 333 Lecture 9 - intro to C++

Inheritance and Polymorphism

JAVA MOCK TEST JAVA MOCK TEST II

Midterm Review. PIC 10B Spring 2018

CS 112 Introduction to Programming

CSE 333. Lecture 11 - constructor insanity. Hal Perkins Paul G. Allen School of Computer Science & Engineering University of Washington

Object Oriented Software Design II

Chapter 14 Abstract Classes and Interfaces

C++ Programming: Polymorphism

Object Oriented Software Design II

Critique this Code. Hint: It will crash badly! (Next slide please ) 2011 Fawzi Emad, Computer Science Department, UMCP

Object Oriented Design

Data Structures (list, dictionary, tuples, sets, strings)

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

Lecture 15: Even more pointer stuff Virtual function table

Transcription:

C++ Inheritance I CSE 333 Spring 2018 Instructor: Justin Hsia Teaching Assistants: Danny Allen Dennis Shao Eddie Huang Kevin Bi Jack Xu Matthew Neldam Michael Poulain Renshu Gu Robby Marver Waylon Huang Wei Lin

Administrivia No exercise released today! Next exercise on inheritance released on Wednesday hw3 is due in two Thursdays (5/17) Get started early! Section this week will also help you get started Midterm grading: scores released soon-ish? Submit regrade requests via Gradescope for each subquestion These go to different graders Regrade requests open until end of Thursday (5/10) Exam will be curved up (free points for everyone!) 2

Lecture Outline C++ Inheritance Review of basic idea Dynamic Dispatch vtables and vptr Reference: C++ Primer, Chapter 15 3

Stock Portfolio Example A portfolio represents a person s financial investments Each asset has a cost (i.e. how much was paid for it) and a market value (i.e. how much it is worth) The difference between the cost and market value is the profit (or loss) Different assets compute market value in different ways A stock that you own has a ticker symbol (e.g. GOOG ), a number of shares, share price paid, and current share price A dividend stock is a stock that also has dividend payments Cash is an asset that never incurs a profit or loss (Credit: thanks to Marty Stepp for this example) 4

Design Without Inheritance One class per asset type: Stock symbol_ total_shares_ total_cost_ current_price_ GetMarketValue() GetProfit() GetCost() DividendStock symbol_ total_shares_ total_cost_ current_price_ dividends_ GetMarketValue() GetProfit() GetCost() Cash amount_ GetMarketValue() Redundant! Cannot treat multiple investments together e.g. can t put in an array or vector of different assets Sample code for separate classes in initial.tar 5

Inheritance A parent-child is-a relationship between classes A child (derived class) extends a parent (base class) Benefits: Code reuse Children can automatically inherit code from parents Polymorphism Ability to redefine existing behavior but preserve the interface Children can override the behavior of the parent Others can make calls on objects without knowing which part of the inheritance tree it is in Extensibility Children can add behavior 6

Design With Inheritance Asset (abstract) Stock symbol_ total_shares_ total_cost_ current_price_ GetMarketValue() GetProfit() GetCost() GetMarketValue() GetProfit() GetCost() DividendStock symbol_ total_shares_ total_cost_ current_price_ dividends_ GetMarketValue() GetProfit() GetCost() Cash amount_ GetMarketValue() 7

Terminology Java Superclass Subclass C++ Base Class Derived Class Mean the same things and you ll hear both 8

Review: Access Modifiers public: visible to all other classes protected: visible to current class and its derived classes private: visible only to the current class 9

Derivation List Comma-separated list of classes to inherit from: #include "BaseClass.h" class Name : public BaseClass {... Focus on single inheritance, but multiple inheritance possible Almost always you will want public inheritance Acts like extends does in Java Any member that is non-private in the base class is the same in the derived class; interface and implementation inheritance Except that constructors, destructors, copy constructor, and assignment operator are never inherited 10

Back to Stocks Stock symbol_ total_shares_ total_cost_ current_price_ GetMarketValue() GetProfit() GetCost() BASE DividendStock symbol_ total_shares_ total_cost_ current_price_ dividends_ GetMarketValue() GetProfit() GetCost() DERIVED 11

Back to Stocks Stock symbol_ total_shares_ total_cost_ current_price_ GetMarketValue() GetProfit() GetCost() Stock symbol_ total_shares_ total_cost_ current_price_ GetMarketValue() GetProfit() GetCost() DividendStock dividends_ GetMarketValue() GetProfit() GetCost() PayDividend() A derived class: Inherits the behavior and state of the base class Overrides some of the base class member functions Extends the base class with new member functions, variables 12

Dynamic Dispatch Usually, when a derived function is available to an object, we want the derived function to be invoked This requires a run time decision of what code to invoke This is similar to Java A member function invoked on an object should be the most-derived function accessible to the object s visible type Can determine what to invoke from the object itself 13

Requesting Dynamic Dispatch Prefix the member function declaration with the virtual keyword Derived/child functions don t need to repeat virtual, but it traditionally has been good style to do so This is how method calls work in Java (no virtual keyword needed) override keyword (C++11) Tells compiler this method should be overriding an inherited virtual function good to use if available Prevents overloading vs. overriding bugs Both of these are optional in derived classes Be consistent and follow local conventions 14

Dynamic Dispatch Example When a member function is invoked on an object: The most-derived function accessible to the object s visible type is invoked (decided at run time) double DividendStock::GetMarketValue() const { return get_shares() * get_share_price() + dividends_; } double DividendStock::GetProfit() const { return GetMarketValue() GetCost(); } DividendStock.cc double Stock::GetMarketValue() const { return get_shares() * get_share_price(); } double Stock::GetProfit() const { return GetMarketValue() GetCost(); } Stock.cc 15

Dynamic Dispatch Example #include "Stock.h" #include "DividendStock.h" DividendStock dividend(); DividendStock* ds = &dividend; Stock* s = &dividend; // why is this allowed? // Invokes DividendStock::GetMarketValue() ds->getmarketvalue(); // Invokes DividendStock::GetMarketValue() s->getmarketvalue(); // invokes Stock::GetProfit(), since that method is inherited. // Stock::GetProfit() invokes DividendStock::GetMarketValue(), // since that is the most-derived accessible function. s->getprofit(); 16

Most-Derived class A { public: // Foo will use dynamic dispatch virtual void Foo(); class B : public A { public: // B::Foo overrides A::Foo virtual void Foo(); class C : public B { // C inherits B::Foo() void Bar() { A* a_ptr; C c; } a_ptr = &c; // Whose Foo() is called? a_ptr->foo(); 17

Peer Instruction Question Whose Foo() is called? Vote at http://pollev.com/justinh Q1 Q2 A. A B B. A D C. B B D. B D E. We re lost void Bar() { A* a_ptr; C c; E e; } // Q1: a_ptr = &c; a_ptr->foo(); // Q2: a_ptr = &e; a_ptr->foo(); class A { public: virtual void Foo(); class B : public A { public: virtual void Foo(); class C : public B { class D : public C { public: virtual void Foo(); class E : public C { 18

How Can This Possibly Work? The compiler produces Stock.o from just Stock.cc It doesn t know that DividendStock exists during this process So then how does the emitted code know to invoke Stock::GetMarketValue() or DividendStock::GetMarketValue()? Function pointers virtual double Stock::GetMarketValue() const; virtual double Stock::GetProfit() const; Stock.h double Stock::GetMarketValue() const { return get_shares() * get_share_price(); } double Stock::GetProfit() const { return GetMarketValue() GetCost(); } Stock.cc 19

vtables and the vptr If a class contains any virtual methods, the compiler emits: A virtual function table (vtable) for the class Contains a function pointer for each virtual method in the class The pointers in the vtable point to the most-derived function for that class A virtual table pointer (vptr) for each object instance A pointer to a virtual table as a hidden member variable When the object s constructor is invoked, the vptr is initialized to point to the vtable for the object s class Thus, the vptr remembers what class the object is 20

351 Throwback: Dynamic Dispatch Point object header vtable ptr x y Point vtable: p??? 3DPoint object code for Point() code for Point s sameplace() header vtable x y z 3DPoint vtable: code for sayhi() code for 3DPoint s sameplace() Java: Point p =???; return p.sameplace(q); C pseudo-translation: // works regardless of what p is return p->vtable[1](p, q); 21

vtable/vptr Example class Base { public: virtual void f1(); virtual void f2(); class Der1 : public Base { public: virtual void f1(); class Der2 : public Base { public: virtual void f2(); Base b; Der1 d1; Der2 d2; Base* b0ptr = &b; Base* b1ptr = &d1; Base* b2ptr = &d2; b0ptr->f1(); // b0ptr->f2(); // b1ptr->f1(); // b1ptr->f2(); // d2.f1(); // b2ptr->f1(); // b2ptr->f2(); // 22

vtable/vptr Example b object instances vptr class vtables Base f1() f2() compiled code Base::f1() push %rbp... Base b; Der1 d1; Der2 d2; Base* b2ptr = &d2; d1 d2 vptr vptr Der1 f1() f2() Der2 f1() f2() Base::f2() push %rbp... Der1::f1() push %rbp... Der2::f2() push %rbp... d2.f1(); // d2.vptr --> // Der2.vtable.f1 --> // Base::f1() b2ptr->f1(); // b2ptr --> // d2.vptr --> // Der2.vtable.f1 --> // Base::f1() 23

Let s Look at Some Actual Code Let s examine the following code using objdump g++ -g -o vtable vtable.cc objdump -CDS vtable > vtable.d class Base { public: virtual void f1(); virtual void f2(); vtable.cc class Der1 : public Base { public: virtual void f1(); int main(int argc, char** argv) { Der1 d1; d1.f1(); Base* bptr = &d1; bptr->f1(); } 24