CPS 100 2.1 Inheritance and the Yahtzee program l In version of Yahtzee given previously, scorecard.h held information about every score-card entry, e.g.,

Slides:



Advertisements
Similar presentations
CPA: C++ Polymorphism Copyright © 2007 Mohamed Iqbal Pallipurath Overview of C++ Polymorphism Two main kinds of types in C++: native and user-defined –User-defined.
Advertisements

C++ Inheritance Gordon College CPS212. Basics OO-programming can be defined as a combination of Abstract Data Types (ADTs) with Inheritance and Dynamic.
Slides 4/22 COP Topics Final Exam Review Final Exam The final exam is Friday, April 29 th at 10:00 AM in the usual room No notes, books, calculators,
The Bridge Pattern.. Intent Decouple an abstraction from its implementation so that the two can vary independently Also known as: Handle/Body.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
OOP Etgar 2008 – Recitation 71 Object Oriented Programming Etgar 2008 Recitation 7.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter N - 1 Chapter 13 Polymorphism is-a relationships Interfaces.
C++ Polymorphism Systems Programming. Systems Programming: Polymorphism 2   Polymorphism Examples   Relationships Among Objects in an Inheritance.
CPS 108 : Spring From C++ to Java l Java history: Oak, toaster-ovens, internet language, panacea  Not really a standard language like C++  Arguably.
Inheritance. Types of Inheritance Implementation inheritance means that a type derives from a base type, taking all the base type’s member fields and.
Abstract classes and Interfaces. Abstract classes.
C++ Object Oriented 1. Class and Object The main purpose of C++ programming is to add object orientation to the C programming language and classes are.
1 Data Structures - CSCI 102 CS102 C++ Polymorphism Prof Tejada.
1 Virtual Functions and Polymorphism Chapter What You Will Learn What is polymorphism? How to declare and use virtual functions for abstract classes.
Inheritance in C++ CS-1030 Dr. Mark L. Hornick.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Taken from slides of Starting Out with C++ Early Objects Seventh Edition.
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page 1 Virtual Functions Polymorphism Abstract base classes.
Polymorphism &Virtual Functions
(C) 2010 Pearson Education, Inc. All rights reserved. Java™ How to Program, 8/e.
CSE 332: C++ templates This Week C++ Templates –Another form of polymorphism (interface based) –Let you plug different types into reusable code Assigned.
CPS What’s easy, hard, first? l Always do the hard part first. If the hard part is impossible, why waste time on the easy part? Once the hard part.
Inheritance Joe Meehean. Object Oriented Programming Objects state (data) behavior (methods) identity (allocation of memory) Class objects definition.
Inheritance and Class Hierarchies Ellen Walker CPSC 201 Data Structures Hiram College.
1 Java Inheritance. 2 Inheritance On the surface, inheritance is a code re-use issue. –we can extend code that is already written in a manageable manner.
C++ Review Classes and Object Oriented Programming Parasol Lab, Texas A&M University.
Object Oriented Programming with C++/ Session 6 / 1 of 44 Multiple Inheritance and Polymorphism Session 6.
CSE 425: Object-Oriented Programming I Object-Oriented Programming A design method as well as a programming paradigm –For example, CRC cards, noun-verb.
CPS Anagram: Using Normalizers l How can we normalize an Anaword object differently?  Call normalize explicitly on all Anaword objects  Have.
RIT Computer Science Dept. Goals l Inheritance l Modifiers: private, public, protected l Polymorphism.
1 Inheritance. 2 Why use inheritance?  The most important aspect of inheritance is that it expresses a relationship between the new class and the base.
CS 106 Introduction to Computer Science I 04 / 23 / 2010 Instructor: Michael Eckmann.
Chapter 10 Inheritance and Polymorphism
Programming in Java CSCI-2220 Object Oriented Programming.
Inheritance Revisited Other Issues. Multiple Inheritance Also called combination--not permitted in Java, but is used in C++ Also called combination--not.
APCS Workshop 1 Why is programming fun? What delights may its practitioner expect as a reward? First is the sheer joy of making things Second is the pleasure.
Object Oriented Programming
Interfaces About Interfaces Interfaces and abstract classes provide more structured way to separate interface from implementation
CS 106 Introduction to Computer Science I 04 / 18 / 2008 Instructor: Michael Eckmann.
Interfaces F What is an Interface? F Creating an Interface F Implementing an Interface F What is Marker Interface?
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Overview of C++ Polymorphism
OBJECT ORIENTED PROGRAMMING. Design principles for organizing code into user-defined types Principles include: Encapsulation Inheritance Polymorphism.
CompSci Reading from Files  import java.io.File;  Declare a file File fileOfCats = new File(”cats.txt”);  Use file – pass it as an argument to.
Recap Introduction to Inheritance Inheritance in C++ IS-A Relationship Polymorphism in Inheritance Classes in Inheritance Visibility Rules Constructor.
Author: DoanNX Time: 45’.  OOP concepts  OOP in Java.
POLYMORPHISM Chapter 6. Chapter Polymorphism  Polymorphism concept  Abstract classes and methods  Method overriding  Concrete sub classes and.
Chapter 9: Continuing Classes By Matt Hirsch. Table Of Contents 1.Static Fields and Methods 2.Inheritance I. Recycle Code with Inheritance II. Overriding.
CPS Anagram: Using Normalizers l How can we normalize an Anaword object differently?  Call normalize explicitly on all Anaword objects  Have.
Polymorphism & Virtual Functions 1. Objectives 2  Polymorphism in C++  Pointers to derived classes  Important point on inheritance  Introduction to.
CSCI-383 Object-Oriented Programming & Design Lecture 17.
Object-Oriented Programming Review 1. Object-Oriented Programming Object-Oriented Programming languages vary but generally all support the following features:
Abstract classes only used as base class from which other classes can be inherit cannot be used to instantiate any objects are incomplete Classes that.
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
Design issues for Object-Oriented Languages
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Inheritance and Polymorphism
Java Programming Language
Virtual Functions Department of CSE, BUET Chapter 10.
Week 6 Object-Oriented Programming (2): Polymorphism
Polymorphism CMSC 202, Version 4/02.
Overview of C++ Polymorphism
Java Programming: From the Ground Up
Java String Class String is a class
Jim Fawcett CSE687 – Object Oriented Design Spring 2014
C++ Polymorphism Reference and pointer implicit type casting
C++ Object Oriented 1.
Lecture 6: Polymorphism
Static Binding Static binding chooses the function in the class of the base class pointer, ignoring any versions in the class of the object actually.
Presentation transcript:

CPS Inheritance and the Yahtzee program l In version of Yahtzee given previously, scorecard.h held information about every score-card entry, e.g., fullhouse, small straight, etc.  Changing the.h requires recompiling all files that include it, either directly or indirectly  Consequences of large-scale recompiling? What about building large programs (word, XP, etc.) l Changes made in several places in scorecard.cpp as well  String for description, code for scoring, order of entries in.h file  Code in different places, related, must be synchronized l Inheritance is an answer to problem of avoiding recompiling, facilitating testing, keeping related code together

CPS Benefits of inheritance, interfaces l Suppose you learn about a new class WebStream that conforms to the input stream interface (cin, ifstream, …)  Can you write code to read words from a web page?  Can you write code to read lines from a web page? Chars? l Can you use existing word counting code to read from a web page instead of from a file, e.g., in readwords.cpp? void readWords(istream& input) {…} l Why can we pass cin, ifstream, WebStream, etc.?  Inheritance, combined with late-binding  What type of variable according to compiler? Runtime?

CPS Why inheritance? l Add new shapes easily without changing much code  Shape * sp = new Circle();  Shape * sp2 = new Square(); l abstract base class:  interface or abstraction  pure virtual function l concrete subclass  implementation  provide a version of all pure functions l “is-a” view of inheritance  Substitutable for, usable in all cases as-a shape mammal ScoreEntry FullHouse, LargeStraight User’s eye view: think and program with abstractions, realize different, but conforming implementations, don’t commit to something concrete until as late as possible

CPS Code snippets from old version l Old version of scoreentry.h class ScoreEntry { public: enum Kind{ ones, twos, threes, fours, fives, sixes, kind3, kind4 fullhouse, smallstraight,largestraight,yahtzee, chance }; // … l Old version of scorecard.cpp ScoreCard::ScoreCard() { myCount = ScoreEntry::numEntries(); for(int k=0; k < myCount; k++) { myEntries.push_back( ScoreEntry(static_cast (k))); }

CPS Yahtzee specifics l In new version each score-card entry (almost) is a class  Similar entries might be one class, e.g., ones, twos, … sixes  See aboveline.h, what about three/four/five of a kind? l In ScoreCard how do create all the entries on a card?  Allocate an instance of each entry using new  Creates object pointed to by a ScoreEntry pointer How can ScoreEntry pointer point at SmallStraight? How can ScoreEntry pointer point at FullHouse? Nothing? l In creating a new score-card entry, do we modify existing header files? Existing.cpp files? Benefits?  What must be recompiled when adding small straight?

CPS Guidelines for using inheritance l Create a base/super/parent class that specifies the behavior that will be implemented in subclasses  Most/All functions in base class may be virtual Often pure virtual (= 0 syntax), subclasses must implement  Subclasses do not need to specify virtual, but good idea May subclass further, show programmer what’s going on  Subclasses specify inheritance using : public Base C++ has other kinds of inheritance, stay away from these  Must have virtual destructor in base class l Inheritance models “is-a” relationship, a subclass is-a parent- class, can be used-as-a, is substitutable-for  Standard examples include animals and shapes

CPS Inheritance guidelines/examples l Virtual function binding is determined at run-time  Non-virtual function binding (which one is called) determined at compile time  Need compile-time, or late, or polymorphic binding  Small overhead for using virtual functions in terms of speed, design flexibility replaces need for speed Contrast Java, all functions “virtual” by default l In a base class, make all functions virtual  Allow design flexibility, if you need speed you’re wrong, or do it later l In C++, inheritance works only through pointer or reference  If a copy is made, all bets are off, need the “real” object

CPS See students.cpp, school.cpp l Base class student doesn’t have all functions virtual  What happens if subclass uses new name() function? name() bound at compile time, no change observed l How do subclass objects call parent class code?  Use class::function syntax, must know name of parent class l Why is data protected rather than private?  Must be accessed directly in subclasses, why?  Not ideal, try to avoid state in base/parent class: trouble What if derived class doesn’t need data?

CPS Inheritance (language independent) l First view: exploit common interfaces in programming  Streams in C++, iterators in Tapestry classes Iterators in STL/C++ share interface by convention/templates  Implementation varies while interface stays the same l Second view: share code, factor code into parent class  Code in parent class shared by subclasses  Subclasses can override inherited method Can subclasses override and call? l Polymorphism/late(runtime) binding (compare: static)  Actual function called determined when program runs, not when program is compiled

CPS Inheritance guidelines in C++ l Inherit from Abstract Base Classes (ABC)  one pure virtual function needed (=0) Subclasses must implement, or they’re abstract too  must have virtual destructor implemented  can have pure virtual destructor implemented, but not normally needed l Avoid protected data, but sometimes this isn’t possible  data is private, subclasses have it, can’t access it  keep protected data to a minimum l Single inheritance, assume most functions are virtual  multiple inheritance ok when using ABC, problem with data in super classes  virtual: some overhead, but open/closed principle intact

CPS Inheritance Heuristics l A base/parent class is an interface  Subclasses implement the interface Behavior changes in subclasses, but there’s commonality  The base/parent class can supply some default behavior Derived classes can use, override, both  The base/parent class can have state Protected: inherited and directly accessible Private: inherited but not accessible directly  Abstract base classes are a good thing l Push common behavior as high up as possible in an inheritance hierarchy l If the subclasses aren’t used polymorphically (e.g., through a pointer to the base class) then the inheritance hierarchy is probably flawed

CPS Inheritance Heuristics in C++ l One pure virtual (aka abstract) function makes a class abstract  Cannot be instantiated, but can be constructed (why?)  Default in C++ is non-virtual or monomorphic Unreasonable emphasis on efficiency, sacrifices generality If you think subclassing will occur, all methods are virtual  Must have virtual destructor, the base class destructor (and constructor) will be called l We use public inheritance, models is-a relationship  Private inheritance means is-implemented-in-terms-of Implementation technique, not design technique Derived class methods call base-class methods, but no “usable-as-a” via polymorphism