Inheritance Basics. Inheritance (with C++) Base class example: Employee. Inheritance begets hierarchies. Writing derived classes

Similar documents
Inheritance (with C++)

Virtual functions concepts

Chapter 15. Polymorphism and Virtual Functions. Copyright 2010 Pearson Addison-Wesley. All rights reserved

Inheritance. Overview. Chapter 15 & additional topics. Inheritance Introduction. Three different kinds of inheritance

Inheritance. Chapter 15 & additional topics

Chapter 14. Inheritance. Slide 1

Chapter 14 Inheritance. GEDB030 Computer Programming for Engineers Fall 2017 Euiseong Seo

Inheritance. Chapter 15 & additional topics

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

Object Oriented Programming. CISC181 Introduction to Computer Science. Dr. McCoy. Lecture 27 December 8, What is a class? Extending a Hierarchy

Ch 14. Inheritance. September 10, Prof. Young-Tak Kim

Data Structures and Other Objects Using C++

Comp 249 Programming Methodology

Java Object Oriented Design. CSC207 Fall 2014

Intermediate Programming

Inheritance. OOP components. Another Example. Is a Vs Has a. Virtual Destructor rule. Virtual Functions 4/13/2017

Object Oriented Programming

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

INHERITANCE. Spring 2019

Inheritance and Polymorphism

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

CS-202 Introduction to Object Oriented Programming

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

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

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

Polymorphism Part 1 1

Chapter 7. Inheritance

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017

Data Abstraction. Hwansoo Han

Lecture 5: Inheritance

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

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

Inheritance and Interfaces

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

Polymorphism. Miri Ben-Nissan (Kopel) Miri Kopel, Bar-Ilan University

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

Making New instances of Classes

Module 10 Inheritance, Virtual Functions, and Polymorphism

Object Oriented Programming in Java. Jaanus Pöial, PhD Tallinn, Estonia

CSE 307: Principles of Programming Languages

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

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

Object Oriented Programming COP3330 / CGS5409

9/10/2018 Programming Data Structures Inheritance

CS313D: ADVANCED PROGRAMMING LANGUAGE

Inheritance, Polymorphism, and Interfaces

CMSC202 Computer Science II for Majors

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

VIRTUAL FUNCTIONS Chapter 10

CS11 Introduction to C++ Fall Lecture 7

Super-Classes and sub-classes

What is Inheritance?

Inheritance, Polymorphism and the Object Memory Model

Fast Introduction to Object Oriented Programming and C++

Class Sale. Represents sales of single item with no added discounts or charges. Notice reserved word "virtual" in declaration of member function bill

Instantiation of Template class

Programming II (CS300)

CS313D: ADVANCED PROGRAMMING LANGUAGE

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

G Programming Languages - Fall 2012

What are the characteristics of Object Oriented programming language?

Derived Classes in C++

ITI Introduction to Computing II

CS111: PROGRAMMING LANGUAGE II

ITI Introduction to Computing II

Chapter 15: Inheritance, Polymorphism, and Virtual Functions

Inheritance Motivation

ECE 122. Engineering Problem Solving with Java

24. Inheritance. Java. Fall 2009 Instructor: Dr. Masoud Yaghini

CMSC 132: Object-Oriented Programming II. Inheritance

Object Oriented Software Design II

Inheritance, and Polymorphism.

Why use inheritance? The most important slide of the lecture. Programming in C++ Reasons for Inheritance (revision) Inheritance in C++

22. Inheritance. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

Object Oriented Software Design II

Lecture Notes on Programming Languages

index.pdf January 21,

CSSE 220 Day 15. Inheritance. Check out DiscountSubclasses from SVN

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

Introduction to C++ Introduction to C++ Dr Alex Martin 2013 Slide 1

QUIZ. How could we disable the automatic creation of copyconstructors

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

COP 3330 Final Exam Review

CS 11 java track: lecture 3

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

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

CS 251 Intermediate Programming Inheritance

Object Oriented Programming COP3330 / CGS5409

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

VALLIAMMAI ENGINEERING COLLEGE

5/24/12. Introduction to Polymorphism. Chapter 8. Late Binding. Introduction to Polymorphism. Late Binding. Polymorphism and Abstract Classes

C++ Programming: Polymorphism

QUIZ. How could we disable the automatic creation of copyconstructors

Chapter 5 Object-Oriented Programming

ENCAPSULATION AND POLYMORPHISM

Building custom components IAT351

Object Oriented Programming. Java-Lecture 11 Polymorphism

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

Inheritance and object compatibility

Transcription:

Inheritance (with C++) Starting to cover Savitch Chap. 15 More OS topics in later weeks (memory concepts, libraries) Inheritance Basics A new class is inherited from an existing class Existing class is termed the base class It is the "general" class (a.k.a. superclass, or parent) New class is termed the derived class It is the "specific" class (a.k.a. subclass, or child) Automatically has (i.e., "inherits") all of the base class's member functions and variables Can define additional member functions and variables And override inherited virtual functions (but that's a later topic) Inheritance begets hierarchies "Is a" relationships Imagine: class Basketball is derived from class Ball Then: any Basketball is a Ball Reverse not always true: a Ball can be a Football, or a Baseball, or Base class example: Employee class Employee { Employee( ); Employee(string thename, string thessn); string getname( ) const; string getssn( ) const; double getnetpay( ) const; void setname(string newname); void setssn(string newssn); void setnetpay(double newnetpay); void printcheck( ) const; string name; string ssn; double netpay; ; Derived class: HourlyEmployee class HourlyEmployee : public Employee { // Instantly inherits all methods and data of class Employee HourlyEmployee( ); HourlyEmployee(string thename, string thessn, double thewagerate, double thehours); void setrate(double newwagerate); double getrate( ) const; void sethours(double hoursworked); double gethours( ) const; void printcheck( ); // plan to redefine printcheck function double wagerate; // new data specific to this derived class double hours; ; Writing derived classes 3 possibilities for member functions: Inherit i.e., do nothing Redefine have new method act differently Define new add abilities not in base class at all 2 possibilities for member variables: Inherit though if private, may not directly access/set Define new more data in addition to base class data Notice: cannot redefine member variables attempts to do so will create "shadow variables" i.e., just creates a new variable with the same name, effectively hiding the inherited one usually a mistake

Derived class constructors A base class constructor is always invoked first i.e., first task of derived class constructor's initialization list If no explicit call, base class default constructor will be called implicitly (compile error if base class has no default ctor) Must explicitly call to use an alternative base class ctor Syntax: BaseClassName(arg1, arg2, ) Derived Employee example: HourlyEmployee::HourlyEmployee(string name, string number, double rate, double hours) : Employee(name, number), wagerate(rate), hours(hours) { Properly initializes name, ssn: private Employee data A subclass object's composition Remember: a derived class definition just defines part of the resulting object The rest of the object is the base class portion HourlyEmployee name: ssn: netpay: wagerate: hours: Employee portion Redefining overloading Redefining only applies to a derived class Same parameter list (i.e., same "signature") Essentially "re-writes" the same function Overloading can happen in base or derived Different parameter list different signature Defining a new function with the same name Recall definition of a signature: Name(parameter list) Does not include return type, and '&' ignored Accessing redefined base function A redefined base class definition is not "lost" Employee jane; HourlyEmployee sally; jane.printcheck(); // Employee function sally.printcheck(); // HourlyEmployee function sally.employee::printcheck(); // uses scope resolution to call Employee function! Often done while implmenting derived class let base function do some of the work Some functions are not inherited All "normal" functions in the base class are inherited in the derived class The exceptions ("abnormal" functions?): Constructors and destructor And assignment operator Compiler generates default versions if you don't redefine them in the derived class But remember that can be problematic if pointing to dynamic memory, so often should redefine Subclass operator= and copy ctor Although not inherited, a derived class typically must use the base class's versions e.g., an operator= in class D : public B D& D::operator=(const D &right) { // first call assignment operator of base class to take // care of all the inherited member variables B::operator=(right);... // then set new variables of derived class Copy ctor must use base class version too D::D(const D &other) : B(other),...{

Destructors in derived classes Easy to write if base class dtor is correct No need to call base class dtor because it is called automatically at the end of the derived class s dtor So derived class destructors need only worry about derived class variables Usual purpose: release resources allocated during the object's life Let base class dtor handle inherited resources Examples: PFArrayD and Bak Base class PFArrayD: ~mikec/cs32/demos/ SavitchAbsolute_ch14/ PFArrayD.h Stores a pointer to a double array on free store Array has a fixed capacity after construction Has mgr., other functions, plus [] and = ops Derived class PFArrayDBak: Has pointer to its own array can be used to backup and restore data in base class's array Redefines ctors, dtor and operator= PFArrayDBak Writing derivable classes Always provide a constructor that can be called with no arguments Control subclass' access to member variables and functions as appropriate three choices: public members are accessible to all other classes private members are not directly accessible to any other class should be used for most variables, and also appropriate for "helper" functions A third choice is protected member access Only subclasses (those derived from this one) can access Some consider it bad OOP practice violates info hiding protected / private inheritance Note: rarely used; frankly a little weird Destroys is a relation of derived class object Protected inheritance all public members in the base class become protected members in the derived class class SalariedEmployee : protected Employee { Private inheritance all members in the base class become private in the derived class class SalariedEmployee : private Employee { Many more inheritance issues For instance: Sometimes it is better to use has a instead of is a relationship Means one class has an object of another class Generally a more flexible design Can also do multiple inheritance in C++ class ClockRadio : public Radio, public AlarmClock; Tricky though (more later, after virtual keyword) Slicing and upcasts more to come Virtual functions concepts Virtual: exists in essence though not in fact Idea is that a virtual function can be used before it is defined And it might be defined many, many ways! Relates to OOP concept of polymorphism Associate many meanings to one function Implemented by dynamic binding A.k.a. late binding happens at run-time

Polymorphism example: figures Imagine classes for several kinds of figures Rectangles, circles, and ovals (to start) All derive from one base class: Figure All Figure objects inherit: void draw() Of course, each one implements it differently! Rectangle r; Circle c; r.draw(); // Calls Rectangle class s draw() c.draw(); // Calls Circle class s draw Nothing new here yet Figures example cont. center() Consider that base class Figure has functions that apply to all figures e.g., center(): moves figure to screen center Erases existing drawing, then re-draws the figure So Figure::center() uses draw() to re-draw But which draw() function will be used? We re implementing base class center() function, so we have to use the base class draw() function. Right? Actually, it turns out the answer depends on how draw() is handled in the base class Poor solution: base works hard Figure class tries to implement draw to work for all (known) figures First devise a way to identify a figure s type Then Figure::draw() uses conditional logic: if ( /* the Figure is a Rectangle */ ) Rectangle::draw(); else if ( /* the Figure is a Circle */ ) Circle::draw();... But what if a new kind of figure comes along? e.g., how to handle a derived class Triangle? Better solution: virtual function Base class declares that the function is virtual: virtual void draw() const; Remember it means draw() exists in essence Such a declaration tells compiler I don t know how this function is implemented, so wait until it is used in a program, and then get its implementation from the object instance. The instance will exist in fact (eventually) Therefore, so will the implementation at that time! Function binding happens late dynamically Another virtual function example (Sale, DiscountSale, Display 15.11) Record-keeping system for auto parts store Track sales, compute daily gross, other stats All based on data from individual bills of sale Problem: lots of different types of bills Idea start with a very general Sale class that has a virtual bill() function: virtual double bill() const; Rest of idea many different types of sales will be added later, and each type will have its own version of the bill() function Sale functions: savings and op < double Sale::savings(const Sale &other) const { return (bill() other.bill()); bool operator < (const Sale &first, const Sale &second) { return (first.bill() < second.bill()); Notice both functions use member function bill()!

A class derived from Sale class DiscountSale : public Sale { DiscountSale(); DiscountSale(double price, double discount); double getdiscount() const; void setdiscount(double newdiscount); double bill() const; // implicitly virtual double discount; // inherits price ; DiscountSale s bill() function First note it is automatically virtual Inherited trait, applies to any descendants Also note rude not to declare it explicitly Of course, definition never says virtual: double DiscountSale::bill() const { double fraction = discount/100; return (1 fraction)*getprice(); Must use access method as price is private The power of virtual is actual! e.g., base class Sale written long before derived class DiscountSale Sale had members savings and < before there was any idea of class DiscountSale Yet consider what the following code does DiscountSale d1, d2; d1.savings(d2); // calls Sale s savings function In turn, class Sale s savings function uses class DiscountSale s bill function. Wow! Clarifying some terminology Recall that overloading redefining Now a new term overriding means redefining a virtual function Polymorphism is an OOP concept Overriding gives many meanings to one name Dynamic binding is what makes it all work Thus, as Savitch puts it, polymorphism, late binding, and virtual functions are really all the same topic. Why not all virtual functions? Philosophy issue: pure OOP vs. efficiency All functions are virtual by default in another popular programming language (Java) there must take steps to make functions non-virtual C++ default is non-virtual programmer must explicitly declare (except when inherited trait) Virtual functions have more overhead More storage for class virtual function table Slower a look-up step; less optimization