Chapter 8: Class Relationships

Slides:



Advertisements
Similar presentations
Module 8 “Polymorphism and Inheritance”. Outline Understanding Inheritance Inheritance Diagrams Constructors in Derived Classes Type Compatibility Polymorphism.
Advertisements

© 2006 Pearson Addison-Wesley. All rights reserved9 A-1 Chapter 9 Advanced Java Topics (inheritance review + Java generics)
ITEC200 – Week03 Inheritance and Class Hierarchies.
Creating Classes from Other Classes Chapter 2 Slides by Steve Armstrong LeTourneau University Longview, TX  2007,  Prentice Hall.
© 2006 Pearson Addison-Wesley. All rights reserved9 A-1 Chapter 9 Advanced Java Topics.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
2 Objectives You should be able to describe: Operator Functions Two Useful Alternatives – operator() and operator[] Data Type Conversions Class Inheritance.
Chapter 10 Classes Continued
Polymorphism. Lecture Objectives To understand the concept of polymorphism To understand the concept of static or early binding To understand the concept.
© 2006 Pearson Addison-Wesley. All rights reserved9 A-1 Chapter 9 Advanced Java Topics CS102 Sections 51 and 52 Marc Smith and Jim Ten Eyck Spring 2007.
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.
OOP Languages: Java vs C++
Chapter 12: Adding Functionality to Your Classes.
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.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Taken from slides of Starting Out with C++ Early Objects Seventh Edition.
Chapter 15 – Inheritance, Virtual Functions, and Polymorphism
Chapter 8 More Object Concepts
800 Class Templates Templates are like advanced macros. They are useful for building new classes that depend on already existing user defined classes or.
Inheritance in the Java programming language J. W. Rider.
© 2011 Pearson Addison-Wesley. All rights reserved 9 B-1 Chapter 9 (continued) Advanced Java Topics.
1 Object-Oriented Programming Using C++ CLASS 1. 2 Review of Syllabus Catalog Description –An introduction to object oriented programming techniques using.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver Chapter 8: Class Relationships Data Abstraction & Problem Solving.
Data Structures Using C++ 2E1 Inheritance An “is-a” relationship –Example: “every employee is a person” Allows new class creation from existing classes.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Advanced C++ Topics Chapter 8. CS 308 2Chapter 8 -- Advanced C++ Topics This chapter describes techniques that make collections of reusable software components.
Class Relationships And Reuse Interlude 4 Data Structures and Problem Solving with C++: Walls and Mirrors, Frank Carrano, © 2012.
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
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.
Chapter 6 Lists Plus. What is a Class Template? A class template allows the compiler to generate multiple versions of a class type by using type parameters.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Java Programming, Second Edition Chapter Twelve Advanced Inheritance Concepts.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
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.
Polymorphism and Virtual Functions One name many shapes behaviour Unit - 07.
POLYMORPHISM Chapter 6. Chapter Polymorphism  Polymorphism concept  Abstract classes and methods  Method overriding  Concrete sub classes and.
A First Book of C++ Chapter 12 Extending Your Classes.
Object-Oriented Programming Review 1. Object-Oriented Programming Object-Oriented Programming languages vary but generally all support the following features:
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
Java Programming Fifth Edition Chapter 9 Introduction to Inheritance.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Advanced Java Topics Chapter 9
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
7. Inheritance and Polymorphism
Inheritance and Polymorphism
Object-Oriented Programming
Polymorphism & Virtual Functions
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Types of Programming Languages
Advanced C++ Topics Chapter 8.
Advanced Java Topics Chapter 9 (continued)
Inheritance, Polymorphism, and Interfaces. Oh My
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes
Figure 8.1 Inheritance: Relationships among timepieces.
OOP and ADTs Chapter 14 Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved.
Classes and Data Abstraction
Virtual Functions Department of CSE, BUET Chapter 10.
Advanced Java Topics Chapter 9
Polymorphism Polymorphism
Array-Based Implementations
Polymorphism Polymorphism - Greek for “many forms”
Fundaments of Game Design
Chapter 9 Carrano Chapter 10 Small Java
Today’s Objectives 10-Jul-2006 Announcements Quiz #3
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.
Figure 8.1 Inheritance: Relationships among timepieces.
Presentation transcript:

Chapter 8: Class Relationships Data Abstraction & Problem Solving with C++ Fifth Edition by Frank M. Carrano

Inheritance Revisited A relationship among classes Allows a class to derive the behavior and structure of an existing class

Inheritance Revisited Figure 8-1 Inheritance: Relationships among timepieces

Inheritance Revisited Multiple inheritance A derived class can have more than one base class We will not study this kind of inheritance Figure 8-2 Multiple inheritance

Inheritance Revisited Superclass or base class A class from which another class is derived Subclass, derived class, or descendant class A class that inherits all members of another class Can add new members to those it inherits Can redefine an inherited method of its base class, if the two methods have the same parameter declarations

Inheritance Revisited Benefits of inheritance It enables the reuse of existing classes It reduces the effort necessary to add features to an existing object Figure 8-3 The derived class Ball inherits members of the base class Sphere and redefines and adds methods

Inheritance Revisited The base class’s public methods can be called by An instance of the base class An instance of the derived class The derived class’s methods A derived class inherits all of the base class’s members (except constructors and destructor) An instance of a derived class has all the behaviors of its base class (can call the base class’s public methods) A derived class cannot access the base class’s private data and methods directly by name

Inheritance Revisited Figure 8-4 Early, or static, binding: The compiler determines which version of a method to invoke

Inheritance Revisited In general, a class’s data members should be private Figure 8-5 Access to public, private, and protected sections of a class by a client and a derived class

Membership Categories of a Class Public data and methods can be used by anyone Private data and methods can be used only by methods and friends of the class Protected data and methods can be used only by methods and friends of both the class and any derived class

Kinds of Inheritance Public inheritance Protected inheritance Public and protected members of the base class remain, respectively, public and protected members of the derived class Protected inheritance Public and protected members of the base class are protected members of the derived class

Kinds of Inheritance Private inheritance Public and protected members of the base class are private members of the derived class In all cases, the private section of a base class cannot be accessed by a derived class

Is-a Relationships Public inheritance should imply an is-a relationship Use inheritance only when an is-a relationship exists Object type compatibility You can use an instance of a derived class anywhere you can use an instance of the base class, but not the other way around

Is-a Relationsips If the class Ball is derived from the class Sphere A ball is a sphere Given the following function declaration: void displayDiameter(Sphere thing); The following statements are valid: Ball myBall(5.0, “Volleyball”); displayDiameter(myBall);

Has-a Relationships If the relationship between two classes is not is-a, do not use public inheritance Has-a relationship Also called containment A class has an object as a data member Cannot be implemented using inheritance

Has-a Relationships Example: A has-a relationship between a pen and a ball class Pen { … private: Ball point; };

As-a Relationships Uses private inheritance Example: Implement a stack as a list class Stack: private List Stack can manipulate the items on the stack by using List’s methods The underlying list is hidden from the clients and descendants of the stack

As-a Relationships Private inheritance is useful when A class needs access to the protected members of another class, or If methods in a class need to be redefined

Virtual Methods and Late Binding Late, or dynamic, binding The appropriate version of a polymorphic method is decided at execution time A polymorphic method Has multiple meanings Overrides a method of the superclass The outcome of an operation depends upon the objects on which it acts

Virtual Methods and Late Binding A virtual method in a base class can be overridden in a derived class The overriding method is virtual The methods must have the same declarations A derived class does not need to override an existing implementation of an inherited virtual method

Virtual Methods and Late Binding Generally, a class’s methods should be virtual, unless you do not want any derived class to override them Constructors cannot be virtual Destructors can and should be virtual A virtual method’s return type cannot be overridden

Virtual Methods and Late Binding Every class that defines a virtual method Is extensible: can add capabilities to a derived class without access to the ancestor’s source code Has a virtual method table, or VMT Contains pointers to the versions of the virtual methods that are appropriate for the calling object Is invisible to the programmer Enables late binding

Virtual Methods and Late Binding Figure 8-9 getArea is virtual: (b) myBall.displayStatistics() calls Ball::getArea

Abstract Base Classes A pure virtual method has an undefined body An abstract base class Contains at least one pure virtual method Used only as a base class for other classes Defines a minimum interface for derived classes Has no instances

Abstract Base Classes An abstract base class Should generally omit implementations except for the destructor and methods providing access to private data members Virtual methods usually should be pure Must implement any virtual method that is not pure Provides a default implementation for derived classes

Abstract Base Classes An abstract base class for Sphere class EquidistantShape { public: virtual void setRadius(double newRadius) = 0; virtual double getRadius()const = 0; virtual void displayStatistics() const = 0; …}; Forces a derived class to implement these methods Otherwise, the derived class would be abstract

Friends Functions and classes can be friends of a class C Friend functions are not members of the class C Friend functions can access the private and protected members of the class C Methods of a friend class have access to the private and protected parts of the class C

Friends Input and output functions are often defined as friend functions friend void readSphereData(Sphere &s) Friendship is not inherited A friend of a base class is not automatically a friend of a derived class

Friends A class List can be a friend of the class ListNode List can access ListNode’s private and protected members) class ListNode { private: … // define constructors and data // members item and *next friend class List; };

The ADTs List and Sorted List Revisited Organize commonalities of list ADTs as an abstract base class class BasicADT { public: virtual ~BasicADT(); virtual bool isEmpty() const = 0; virtual int getLength() const = 0; };

The ADTs List and Sorted List Revisited Use public inheritance to derive the class List from BasicADT class List : public BasicADT Define protected methods in List that access its private data members so a derived class can also access them

Implementations of the ADT Sorted List That Use the ADT List Recall the operation contract for the sorted list sortedIsEmpty():boolean {query} sortedGetLength():integer {query} sortedInsert(in newItem:ListItemType,                     out success:boolean) sortedRemove(in index:integer,                          out success :boolean) sortedRetrieve(in index:integer,                          out dataItem:ListItemType,                          out success :boolean) {query} locatePosition(in anItem:ListItemType,                           out isPresent:boolean):integer {query}

Implementations of the ADT Sorted List That Use the ADT List A sorted list is a list class SortedList : public List Figure 8-12 SortedList as a descendant of List

Implementations of the ADT Sorted List That Use the ADT List A sorted list has a list as a member class SortedList … private: List aList; … Figure 8-13 SortedList is composed of an instance of the class List

Implementations of the ADT Sorted List That Use the ADT List A sorted list is implemented as a list class SortedList : private List Figure 8-14 The SortedList class implemented in terms of the List class

Class Templates A class template describes a class in terms of a data-type parameter Example: A header file for a list node #include <cstddef> template <typename T> class List; template <typename T> class ListNode { private: ListNode(): next(NULL) {} . . . T item; ListNode *next; friend class List <T>; };

Class Templates The client specifies an actual data type when declaring an instance of the class template #include “ListT.h” int main() { List<double> floatList; List<char> charList; . . .

Class Templates A class template’s implementation is not compiled separately from the client program The compiler must know the data type that the client is using Any operation required of the actual data type should be clearly documented Templates can have more than one data-type parameter

Overloaded Operators An overloaded operator has more than one meaning Overload common operators for classes to enable a particular operator to work correctly on instances of a class

Overloaded Operators Example: a list Define the equality operator for a list virtual bool operator== (const List& rhs) const Overload the assignment operator to get a deep copy of a list virtual List& operator= (const List& rhs);

Overloading Operators Guidelines for overloading operators You can overload any C++ operator except . .* :: ?: sizeof You cannot define new operators by overloading symbols that are not already operators in C++ You cannot change the standard precedence of a C++ operator or the number of its operands

Overloading Operators Guidelines continued At least one operand of an overloaded operator must be an instance of a class A typical class should overload the assignment, equality, and relational operators = == != < <= > >= You cannot change the number of arguments for an overloaded method

Iterators An iterator is an object that traverses a collection of like objects Common iterator operations Operation Description * Return the item that the iterator currently references ++ Move the iterator to the next item in the list -- Move the iterator to the previous item in the list == Compare two iterators for equality != Compare two iterators for inequality

Iterators A header file for the class ListIterator // List and ListIterator are friend classes of ListNode #include “ListNode.h” class ListIterator { public: ListIterator(const List *aList, ListNode *nodePtr); const ListItemType & operator*(); ListIterator operator++(); bool operator==(const ListIterator& rhs) const; bool operator!=(const ListIterator& rhs) const; friend class List; private: const List *container //ADT associated with iterator ListNode *cur; //current location in collection };

Summary Classes can have ancestor and descendant relationships A derived class inherits all members of the base class, but can access only its public and protected members Use public inheritance only when an is-a relationship exists between classes An instance of a derived class can be used wherever an instance of its base class can be used Type compatible

Summary A method in a derived class redefines a method in the base class if they have the same declarations If the base-class method is virtual, it is overridden by the method in the derived class A virtual method is one that a derived class can override A pure virtual method has an undefined body A class with at least one pure virtual method is called an abstract base class

Summary Early, or static, binding describes a situation whereby a compiler can determine at compilation time the correct method to invoke Late, or dynamic, binding describes a situation whereby the system makes this determination at execution time When a pointer to an object invokes a method, the pointer’s type determines the correct method (early binding); the type of object determines the correct method when the method is virtual (late binding)

Summary Class templates enable you to parameterize the type of a class’s data By overloading an existing C++ operator, you can provide it additional meaning when used with instances of the class Iterators provide an alternative way to cycle through a collection of items