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

Slides:



Advertisements
Similar presentations
Contents o Introduction o Characteristics of Constructor. o Types of constructor. - Default Constructor - Parameterized Constructor - Copy Constructor.
Advertisements

INHERITANCE BASICS Reusability is achieved by INHERITANCE
Inheritance Inheritance Reserved word protected Reserved word super
Inheritance Polymorphism Briana B. Morrison CSE 1302C Spring 2010.
Object-Oriented Programming in C++ Lecture 6 Inheritance.
ACM/JETT Workshop - August 4-5, :Inheritance and Interfaces.
V IRTUAL F UNCTIONS Chapter 10 Department of CSE, BUET 1.
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 8.1 – 8.5.
Encapsulation, Inheritance & Interfaces CSE 115 Spring 2006 February 27, March 1 & 3, 2006.
Reusing Code Private or Protected inheritance. A cool class for array valarray class deals with numeric values, and it supports operation such as summing.
Rossella Lau Lecture 8, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 8: Polymorphism & C++ pointer  Inheritance.
CSE 143 Lecture 3 Inheritance slides created by Marty Stepp
1 CSE 303 Lecture 24 Inheritance in C++, continued slides created by Marty Stepp
Object Oriented Programming C++. ADT vs. Class ADT: a model of data AND its related functions C++ Class: a syntactical & programmatic element for describing.
Virtual Functions Junaed Sattar November 10, 2008 Lecture 10.
1 Data Structures - CSCI 102 CS102 C++ Polymorphism Prof Tejada.
Chapter 15 – Inheritance, Virtual Functions, and Polymorphism
Polymorphism &Virtual Functions
Polymorphism &Virtual Functions 1. Polymorphism in C++ 2 types ▫Compile time polymorphism  Uses static or early binding  Example: Function and operator.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
Inheritance and Class Hierarchies Ellen Walker CPSC 201 Data Structures Hiram College.
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
CSC 142 Computer Science II Zhen Jiang West Chester University
CS212: Object Oriented Analysis and Design Lecture 15: Inheritance in C++ -II.
Week 14 - Monday.  What did we talk about last time?  Introduction to C++  Input and output  Functions  Overloadable  Default parameters  Pass.
Inheritance One of the most powerful features of C++
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.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver Chapter 8: Class Relationships Data Abstraction & Problem Solving.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
Chapter 10 Inheritance and Polymorphism
Copyright © 2012 Pearson Education, Inc. Chapter 15: Inheritance, Polymorphism, and Virtual Functions.
1 Building Java Programs Chapter 9: Inheritance and Interfaces These lecture notes are copyright (C) Marty Stepp and Stuart Reges, They may not be.
Lecture 10 Concepts of Programming Languages Arne Kutzner Hanyang University / Seoul Korea.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Inheritance Objectives: Creating new classes from existing classes The protected modifier Creating class hierarchies Abstract classes Indirect visibility.
Sadegh Aliakbary Sharif University of Technology Spring 2011.
Virtual FunctionstMyn1 Virtual Functions A virtual function is declared in a base class by using the keyword virtual. A function that you declare as virtual.
CS-1030 Dr. Mark L. Hornick 1 Basic C++ State the difference between a function/class declaration and a function/class definition. Explain the purpose.
Inheritance Initialization & Destruction of Derived Objects Protected Members Non-public Inheritance Virtual Function Implementation Virtual Destructors.
Inheritance and Composition Reusing the code and functionality Unit - 04.
Peyman Dodangeh Sharif University of Technology Fall 2014.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 Assignment 3 is due Sunday, the 8 th at 7pm. Problems with assn 3? Discuss at your team meeting tonight.
1 C# - Inheritance and Polymorphism. 2 1.Inheritance 2.Implementing Inheritance in C# 3.Constructor calls in Inheritance 4.Protected Access Modifier 5.The.
Recap Introduction to Inheritance Inheritance in C++ IS-A Relationship Polymorphism in Inheritance Classes in Inheritance Visibility Rules Constructor.
Inheritance in C++ Bryce Boe 2012/08/28 CS32, Summer 2012 B.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
POLYMORPHISM Chapter 6. Chapter Polymorphism  Polymorphism concept  Abstract classes and methods  Method overriding  Concrete sub classes and.
CSE 374 Programming Concepts & Tools Hal Perkins Fall 2015 Lecture 20 – C++ Subclasses and Inheritance.
Copyright 2009 by Pearson Education Building Java Programs Chapter 9: Inheritance and Interfaces Lecture 9-1.
258 3/30/98 CSE 143 Object-Oriented Programming [Chapter 11]
MAITRAYEE MUKERJI Object Oriented Programming in C++: Hierarchy / Inheritance.
CPSC 252Inheritance II Page 1 Inheritance & Pointers Consider the following client code: const int MAXCLOCKS = 2; Clock* clockPtr[ MAXCLOCKS ]; clockPtr[0]
A First Book of C++ Chapter 12 Extending Your Classes.
Java Programming Fifth Edition Chapter 9 Introduction to Inheritance.
Modern Programming Tools And Techniques-I
Inheritance and Polymorphism
Lecture 9-2: Interacting with the Superclass (super);
Java Programming Language
Virtual Functions Department of CSE, BUET Chapter 10.
Polymorphism, Abstract Classes & Interfaces
C++ Inheritance I CSE 333 Spring 2018
CISC/CMPE320 - Prof. McLeod
C++ Inheritance I CSE 333 Summer 2018
Chapter 8: Class Relationships
C++ Inheritance I CSE 333 Autumn 2018
C++ Inheritance I CSE 333 Winter 2019
Lecture 10 Concepts of Programming Languages
Chapter 11 Class Inheritance
CIS 110: Introduction to computer programming
Presentation transcript:

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

2 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 Stock has a symbol (such as "MSFT" for Microsoft), a number of shares, the total cost paid, and a current price per share.  A Dividend Stock is a stock that also gives back dividend payments.  Cash is simply an amount of money. It never incurs profit or loss.

3 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).

4 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.

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

6 Access specifiers declare a member as protected if:  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 directorydescription public visible to all other classes private visible only to the current class (even subclasses cannot directly access it) protected visible to current class and its subclasses

7 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)

8 DividendStock.h #ifndef _DIVIDENDSTOCK_H #define _DIVIDENDSTOCK_H #include #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 public: DividendStock(string symbol, double sharePrice = 0.0); double dividends() const; double marketValue() const; void payDividend(double amountPerShare); }; #endif

9 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)

10 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(); }

11 A problem Client program's old output: value: $ cost: $ profit: $ 0.00 value: $ cost: $ profit: $ value: $ cost: $ profit: $ Client program's new output: value: $ cost: $ profit: $ 0.00 value: $ cost: $ profit: $ value: $ cost: $ profit: $ What happened?

12 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++.)

13 Virtual methods // Stock.h class Stock {... public: virtual double marketValue() const;... };  If you want a method/operator to use dynamic dispatch, put the keyword virtual in 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.

14 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 }

15 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.

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

17 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.