Inheritance Joe Meehean. Object Oriented Programming Objects state (data) behavior (methods) identity (allocation of memory) Class objects definition.

Slides:



Advertisements
Similar presentations
Constructor. 2 constructor The main use of constructors is to initialize objects. A constructor is a special member function, whose name is same as class.
Advertisements

Contents o Introduction o Characteristics of Constructor. o Types of constructor. - Default Constructor - Parameterized Constructor - Copy Constructor.
Inheritance. Many objects have a hierarchical relationship –Examples: zoo, car/vehicle, card game, airline reservation system Inheritance allows software.
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.
Rossella Lau Lecture 8, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 8: Polymorphism & C++ pointer  Inheritance.
Welcome to Constructors and Destructors Prepared By Prepared By : VINAY ALEXANDER ( विनय अलेक्जेण्डर )PGT(CS) KV JHAGRAKHAND.
Virtual Functions Junaed Sattar November 10, 2008 Lecture 10.
Shallow Versus Deep Copy and Pointers Shallow copy: when two or more pointers of the same types point to the same memory – They point to the same data.
CSE 332: C++ Classes From Procedural to Object-oriented Programming Procedural programming –Functions have been the main focus so far Function parameters.
More Classes in C++ Bryce Boe 2012/08/20 CS32, Summer 2012 B.
OOP Languages: Java vs C++
Programming Languages and Paradigms Object-Oriented Programming.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
Chapter 4 Inheritance Bernard Chen Spring Objective IS-A relationships and the allowable changes for derived classes The concept of polymorphism.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and 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.
Copy Control Joe Meehean. More Class Responsibilities When making a new type (i.e., class) we must specify what happens when it is: Copied Assigned Destroyed.
Pointer Data Type and Pointer Variables
Inheritance in C++ CS-1030 Dr. Mark L. Hornick.
1 Classes- Inheritance Multiple Inheritance It is possible to derive a new class from more than one base class. This is called Multiple Inheritance. Under.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
Overview of Previous Lesson(s) Over View  OOP  A class is a data type that you define to suit customized application requirements.  A class can be.
CSE 332: C++ templates This Week C++ Templates –Another form of polymorphism (interface based) –Let you plug different types into reusable code Assigned.
Inheritance. Recall the plant that we defined earlier… class Plant { public: Plant( double theHeight ) : hasLeaves( true ), height (theHeight) { } Plant(
Object Oriented Programming with C++/ Session 6 / 1 of 44 Multiple Inheritance and Polymorphism Session 6.
Hank Childs, University of Oregon May 8th, 2015 CIS 330: _ _ _ _ ______ _ _____ / / / /___ (_) __ ____ _____ ____/ / / ____/ _/_/ ____/__ __ / / / / __.
Copyright © 2012 Pearson Education, Inc. Chapter 13: Introduction to Classes.
Unit IV Unit IV: Virtual functions concepts, Abstracts classes & pure virtual functions. Virtual base classes, Friend functions, Static functions, Assignment.
Chapter 13. Procedural programming vs OOP  Procedural programming focuses on accomplishing tasks (“verbs” are important).  Object-oriented programming.
C++ Review (3) Structs, Classes, Data Abstraction.
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.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
Copyright 2006 Oxford Consulting, Ltd1 February Polymorphism Polymorphism Polymorphism is a major strength of an object centered paradigm Same.
C/C++ 3 Yeting Ge. Static variables Static variables is stored in the static storage. Static variable will be initialized once. 29.cpp 21.cpp.
1 Interfaces and Abstract Classes Chapter Objectives You will be able to: Write Interface definitions and class definitions that implement them.
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
OOP using C Abstract data types How to accomplish the task??? Requirements Details Input, output, process Specify each task in terms of input.
Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives  Inheritance  Virtual Function.
CSci 162 Lecture 10 Martin van Bommel. Procedures vs Objects Procedural Programming –Centered on the procedures or actions that take place in a program.
CPS Inheritance and the Yahtzee program l In version of Yahtzee given previously, scorecard.h held information about every score-card entry, e.g.,
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.
Chapter 1 C++ Basics Review (Section 1.4). Classes Defines the organization of a data user-defined type. Members can be  Data  Functions/Methods Information.
1 Introduction to Object Oriented Programming Chapter 10.
Recap Introduction to Inheritance Inheritance in C++ IS-A Relationship Polymorphism in Inheritance Classes in Inheritance Visibility Rules Constructor.
Object Oriented Programming in C++ Chapter 7 Dynamic Binding.
Class Inheritance Inheritance as an is-a relationship Public derive one class from another Protected access Initializer lists in constructor Upcasting.
ECE 264 Object-Oriented Software Development
Structure A Data structure is a collection of variable which can be same or different types. You can refer to a structure as a single variable, and to.
©Copyrights 2016 Eom, Hyeonsang All Rights Reserved Computer Programming Object Oriented Programming & C++ 1 st Lecture 엄현상 (Eom, Hyeonsang) Department.
Welcome to Constructors and Destructors Prepared By Prepared By : VINAY ALEXANDER ( विनय अलेक्जेण्डर )PGT(CS) KV JHAGRAKHAND.
Introduction to C++ programming Recap- session 1 Structure of C++ program Keywords Operators – Arithmetic – Relational – Logical Data types Classes and.
Seventh step for Learning C++ Programming CLASS Declaration Public & Private Constructor & Destructor This pointer Inheritance.
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.
Constructors and Destructors
Pointer to an Object Can define a pointer to an object:
CS 215 Final Review Ismail abumuhfouz Fall 2014.
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
Andy Wang Object Oriented Programming in C++ COP 3330
Object-Oriented Programming & Design Lecture 18 Martin van Bommel
Review: Two Programming Paradigms
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes
Introduction to Classes
Constructors and Destructors
CISC/CMPE320 - Prof. McLeod
C++ Programming ㅎㅎ String OOP Class Constructor & Destructor.
Introduction to Classes and Objects
ENERGY 211 / CME 211 Lecture 17 October 29, 2008.
SPL – PS4 C++ Advanced OOP.
Presentation transcript:

Inheritance Joe Meehean

Object Oriented Programming Objects state (data) behavior (methods) identity (allocation of memory) Class objects definition defines interface objects are explicitly created (instantiated) from a class

Advantages of OOP Encapsulation related data is stored and modified together implementation separate from interface implementation can easily be modified Abstraction objects viewed by functionality they provide not how they provide it makes building complex software easier

Abstraction Example Roommate offers to drive to beach Car (Abstraction) runs passenger seats cargo space

Abstraction Example

The problem in C++ Say we have a Book class, it has author title retail price calculatePrice method We want to add used books more owners = cheaper could add an owners count to Book We also want to add limited edition books, they have signed adds 20% to price 1 st add 20% to price limited editions should not decrease based on number of owners 6

The problem in C++ Book class is getting pretty complex really represents a lot more than just new books We would like to say a UsedBook is a Book, but we want to calculate its price differently Share all the things UsedBook has in common with Book author title retail price Don’t share the things it does not price calculation 7

Inheritance Can do this using Inheritance sometimes called an “is-a” relationship UsedBook is a Book Book is the base class UsedBook is the derived classes UsedBook is derived from Book sometimes called extends UsedBook extends Book 8

Inheritance Derived classes automatically have all the member data of the base class all the public methods of the base class Derived classes can selectively replace the methods of the base class e.g., calculatePrice() add their own member data add their own member functions 9

Base class Defining a base class exactly the same as any other class Virtual methods methods that can be replaced by derived class syntax: virtual type1 name(type2 arg1, type2 arg2, …) e.g., virtual double calculatePrice() virtual only goes before method declaration, not definition Protected members new access label protected can be accessed by derived classes cannot be accessed by public 10

Base class 11 class Book{ protected: string author_; string title_; double retail_; public: Book(string author, string title, double retail); virtual ~Book(); virtual double calculatePrice(); virtual string getAuthor(); virtual string getTitle(); }

Base class 12 double Book::calculatePrice(){ return retail_; } string Book::getAuthor(){ return author_; } string Book::getTitle(){ return title_; }

Derived class Defining a derived class need to list base class in definition syntax: class classname : access-label base-class { e.g., class UsedBook : public Book { can replace virtual methods of base class, just redefine method e.g., double calculatePrice() can add member variables, just like any other class 13

Derived class Instantiated (an instance of) derived class has two parts base derived access base members like defined right in the derived class If derived class doesn’t redefine virtual functions it still has those functions defined by base class 14

Derived class 15 class UsedBook : public Book{ protected: int prev_owners_; public: UsedBook(string author, string title, double retail, int prev_owners); virtual ~UsedBook(); virtual double calculatePrice(); }

Derived class 16 double UsedBook::calculatePrice(){ double price = retail_; price -= (retail_/5) * prev_owners; return price; }

Questions? 17

Types of inheritance Type of inheritance class UsedBook : access-label Book { can be public, private, or protected Public inheritance members of the base class retain access levels private members still private public members still public any public method defined by base class, also automatically defined for derived class 18

Types of inheritance Type of inheritance class UsedBook : access-label Book { can be public, private, or protected Protected inheritance public members of the base class now protected protected members of the base class still protected private members of the base class still private any public/protected/private method defined by base class automatically defined for the derived class but, can be called by the derived class only (and classes that extend derived class) 19

Types of inheritance Type of inheritance class UsedBook : access-label Book { can be public, private, or protected Private inheritance public & protected members of the base class now private private members of the base class still private any public/protected/private method defined by base class automatically defined for the derived class but, can be called by the derived class only 20

Dynamic Binding Can refer to objects of derived type by base type e.g., Base *p = new Derived(); Does not throw away any part of the derived class Derived class is just pointed at using a base pointer 21 UsedBook ub(...); Book *pb = &ub; //... pb = new LimitedEdition(...);

Dynamic Binding What happens when we call a method on an object using a base pointer? Base method is virtual & defined by derived class, the derived method is called Base method is virtual & not defined by derived class, the base method is called Base method is not virtual & defined by derived class, the base method is called This magic is referred to as dynamic binding 22

The problem Interface set of methods provided by a class What if we just want to define an interface? methods that should be provided by every derived class should not be able to get an instance of base class base class is so abstract, an instance doesn’t make sense 23

Abstract class class that cannot be instantiated How do we make one? define a class with a pure virtual function Pure virtual function function declared but explicitly not defined in base class syntax: virtual type1 name(type2 arg1, type3 arg2, …) = 0 24

Abstract class 25 class BlackJackPlayer { public: virtual bool hold(int hand_total) = 0; };

Abstract class 26 class HoldAt17 : public BlackJackPlayer{ bool hold(int hand_total); }; bool HoldAt17::hold(int hand_total){ return hand_total >= 17; }

Abstract class 27 class HumanPlayer : public BlackJackPlayer{ bool hold(int hand_total); }; bool HumanPlayer::hold(int hand_total){ cout << “Total: “ << hand_total << endl; cout << “Enter h to Hold:”; char key_press; cin >> key_press; return key_press == ‘h’; }

Questions? 28

Inheritance & Copy Control Derived-class synthesized default constructor initializes data members of derived class initializes data members of base class Derived-class default constructor automatically invokes base class default constructor 29 UsedBook::UsedBook() : prev_owners_(0){} // uses Book() to initialize author, title, etc..

Inheritance & Copy Control Passing arguments to the base-class constructor member initialization list may only initialize derived member data initialize base-class member data using base-class constructor 30 UsedBook::UsedBook(string author, string title, double retail, int owners) : prev_owners_(owners), Book(author, title, retail) { }

Inheritance & Copy Control Derived copy constructor if derived class defines copy constructor should copy derived member data use base-class copy constructor to initialize base-class data 31 UsedBook::UsedBook(const UsedBook& orig) : prev_owners_(orig.prev_owners_), Book(orig) { }

Inheritance & Copy Control Derived assignment operator if derived class defines an assignment operator use base-class assignment operator to assign base-class data should clean-up and reinitialize derived member data 32 UsedBook& UsedBook::operator =(const UsedBook& rhs) { if( this != &rhs ){ // call base-class assignment operator Book::operator=(rhs); // assign derived member data prev_owners_ = rhs.prev_owners; } return *this; }

Inheritance & Copy Control Derived destructor define only if derived member data needs explicit cleanup never has to cleanup base-class member data DO NOT CALL BASE CLASS DESTRUCTOR 33 UsedBook::~UsedBook() { // nothing to do }

Inheritance & Copy Control Base-class destructor MUST be virtual otherwise wrong destructor may be called 34 Book *pBook = new UsedBook(...);... delete pBook;

Questions? 35

36