inheritance joe meehean. object oriented programming objects state (data) behavior (methods)...

36
Inheritance Joe Meehean

Upload: joanna-daniels

Post on 29-Dec-2015

219 views

Category:

Documents


2 download

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• Roommate offers to drive to beach• Car (Implementation)• 1993 Honda Accord• Unleaded gas• Manual transmission• Needs oil change in 127 miles

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• 1st 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• 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

Discussion Break