A First Book of C++ Chapter 12 Extending Your Classes.

Slides:



Advertisements
Similar presentations
Copyright © 2012 Pearson Education, Inc. Chapter 15: Inheritance, Polymorphism, and Virtual Functions.
Advertisements

OOP: Inheritance By: Lamiaa Said.
Chapter Objectives You should be able to describe: Assignment Pointers as Class Members Additional Class Features Common Programming Errors.
2 Objectives You should be able to describe: Operator Functions Two Useful Alternatives – operator() and operator[] Data Type Conversions Class Inheritance.
Inheritance, Polymorphism, and Virtual Functions
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation - a language mechanism for restricting access to some.
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++
Programming Languages and Paradigms Object-Oriented Programming.
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
Chapter 12: Adding Functionality to Your Classes.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
1 Inheritance and Polymorphism Chapter 9. 2 Polymorphism, Dynamic Binding and Generic Programming public class Test { public static void main(String[]
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
Pointer Data Type and Pointer Variables
Learners Support Publications Pointers, Virtual Functions and Polymorphism.
Data Structures Using C++ 2E Chapter 3 Pointers and Array-Based Lists.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Taken from slides of Starting Out with C++ Early Objects Seventh Edition.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide
Chapter 11: Inheritance and Composition. Objectives In this chapter, you will: – Learn about inheritance – Learn about derived and base classes – Redefine.
1 Understanding Inheritance COSC 156 C++ Programming Lecture 8.
Object Oriented Programming with C++/ Session 6 / 1 of 44 Multiple Inheritance and Polymorphism Session 6.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 2.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 13: Introduction to Classes.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 13 Introduction to Classes.
OOP: Encapsulation,Abstraction & Polymorphism. What is Encapsulation Described as a protective barrier that prevents the code and data being randomly.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver Chapter 8: Class Relationships Data Abstraction & Problem Solving.
Data Structures Using C++ 2E Chapter 3 Pointers. Data Structures Using C++ 2E2 Objectives Learn about the pointer data type and pointer variables Explore.
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.
Chapter 11: Introduction to Classes. In this chapter you will learn about: – Classes – Basic class functions – Adding class functions – A case study involving.
Programming Fundamentals1 Chapter 7 INTRODUCTION TO CLASSES.
Chapter 10 Inheritance and Polymorphism
Copyright 2006 Oxford Consulting, Ltd1 February Polymorphism Polymorphism Polymorphism is a major strength of an object centered paradigm Same.
Inheritance, Polymorphism, And Virtual Functions Chapter 15.
Chapter 7 Understanding Inheritance. LOGO Objectives  Learn about inheritance and its benefits  Create a derived class  Learn about restrictions imposed.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
What Is Inheritance? Provides a way to create a new class from an existing class New class can replace or extend functionality of existing class Can be.
Copyright © 2012 Pearson Education, Inc. Chapter 15: Inheritance, Polymorphism, and Virtual Functions.
Chapter 10: Introduction to Inheritance. Objectives Learn about the concept of inheritance Extend classes Override superclass methods Call constructors.
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 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.
Chapter 11: Inheritance and Composition. Introduction Two common ways to relate two classes in a meaningful way are: – Inheritance (“is-a” relationship)
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 and Virtual Functions One name many shapes behaviour Unit - 07.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 13: Introduction to Classes.
Programming Fundamentals1 Chapter 7 INTRODUCTION TO CLASSES.
Chapter 12: Pointers, Classes, Virtual Functions, Abstract Classes, and Lists.
Chapter 5 Introduction to Defining Classes Fundamentals of Java.
Design issues for Object-Oriented Languages
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Class Inheritance Part I
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
Inheritance, Polymorphism, and Virtual Functions
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes
Understanding Inheritance
Introduction to Classes
Inheritance, Polymorphism, and Virtual Functions
9: POLYMORPHISM Programming Technique II (SCSJ1023) Jumail Bin Taliba
CISC/CMPE320 - Prof. McLeod
9-10 Classes: A Deeper Look.
Chapter 8: Class Relationships
9-10 Classes: A Deeper Look.
Programming in C# CHAPTER 5 & 6
Presentation transcript:

A First Book of C++ Chapter 12 Extending Your Classes

Objectives In this chapter, you will learn about: –Class Inheritance –Polymorphism –Dynamic Object Creation and Deletion –Pointers as Class Members –Common Programming Errors –UML Class and Object Diagrams A First Book of C++ 4th Edition2

3 Class Inheritance Deriving one class from another class Polymorphism allows redefining how member functions of the same name operate Base class (parent class, or superclass): initial class used as basis for derived class Derived class (child class, or subclass): new class that incorporates all of the data and member functions of its base class –Usually adds new data and function members –Can override any base class function

Class Inheritance (cont'd.) Example of inheritance: three geometric shapes: circle, cylinder, and sphere –Shapes share common characteristic: radius –Can make circle base type for the other two shapes (Figure 12.1) –By convention, arrows always point from derived class to base class Reformulating these shapes as class types, we would make circle base class and derive cylinder and sphere classes from it A First Book of C++ 4th Edition4

5 Class Inheritance (cont'd.)

A First Book of C++ 4th Edition6 Class Inheritance (cont'd.) Simple inheritance –Each derived type has only one base type Multiple inheritance –Derived type has two or more base types Class hierarchies –Illustrate the hierarchy, or order, in which one class is derived from another

A First Book of C++ 4th Edition7 Access Specifications Until now, we have used only private and public access specifiers within class private status ensures that data members can be accessed only by class member functions or friends –Prevents access by any nonclass functions (except friends) –Also precludes access by any derived class functions

A First Book of C++ 4th Edition8 Access Specifications (cont'd.) protected access: third access specification permits only member or friend function access –Permits this restriction to be inherited by any derived class –Derived class defines its inheritance subject to base class’s access restrictions Class-access specifier: listed after colon at start of its declaration section, defines inheritance Table 12.1 lists inherited access restrictions

A First Book of C++ 4th Edition9 Access Specifications (cont'd.)

A First Book of C++ 4th Edition10 Access Specifications (cont'd.) Example: Derive Cylinder class from Circle class // BASE class declaration class Circle { protected: double radius; public: Circle(double = 1.0); // constructor double calcval(); }; // class implementation // constructor Circle::Circle(double r) // constructor { radius = r; } // calculate the area of a circle double Circle::calcval() { return(PI * radius * radius); }

A First Book of C++ 4th Edition11 Access Specifications (cont'd.) Example: Derived Cylinder class // class declaration section where // Cylinder is derived from Circle class Cylinder : public Circle { protected: double length; // add one additional data member and public: // two additional function members Cylinder(double r = 1.0, double l = 1.0) : Circle(r), length(l) {} double calcval(); }; // class implementation double Cylinder::calcval() // this calculates a volume { return (length * Circle::calcval()); // note the base // function call }

Polymorphism Permits same function name to invoke one response in objects of base class and another response in objects of derived class –Example of polymorphism: overriding of base member function using an overloaded derived member function, as illustrated by the calcval() function in Program 12.1 Function binding: determines whether base class or derived class version of function will be used A First Book of C++ 4th Edition12

Polymorphism (cont'd.) Static binding: determination of which function to be called is made at compile time –Used in normal function calls Dynamic binding: determination of which function to be called is made at runtime (via virtual function) Virtual function (Example in Program 12.2): creates pointer to function to be used –Value of pointer variable is not established until function is actually called –At runtime, and on the basis of the object making the call, the appropriate function address is used A First Book of C++ 4th Edition13

Dynamic Object Creation and Deletion Dynamic allocation: amount of storage to be allocated is assigned, as requested, at runtime –Instead of being fixed at compile time –Useful when dealing with lists and objects A First Book of C++ 4th Edition14

Dynamic Object Creation and Deletion (cont'd.) After an object has been dynamically created –It can be accessed only by using the address the new operator returns Example: Checkout *anotherTrans; anotherTrans = new Checkout; Deleting dynamically created objects when their usefulness ends is crucial Memory leak: after an existing object’s address is overwritten with a new object’s address, there’s no way for the system to reclaim the memory A First Book of C++ 4th Edition15

A First Book of C++ 4th Edition16 Pointers as Class Members Class declaration for Program 12.6: list of book titles –Titles accessed as illustrated in Figure 12.7 #include using namespace std; class Book { private: char *title; // a pointer to a book title public: Book(char * = '\0'); // constructor void showtitle(void); // display the title };

A First Book of C++ 4th Edition17 Pointers as Class Members (cont'd.) Implementation section for Program 12.6 –Defines Book() and showtitle() functions // class implementation section Book::Book(char *name) { title = new char[strlen(name)+1]; // allocate memory strcpy(title,name); // store the string } void Book::showtitle(void) { cout << title << endl; }

A First Book of C++ 4th Edition18 Pointers as Class Members (cont'd.) main() function of Program 12.6 int main() { Book book1("Windows Primer"); // create 1st title // 2nd title Book book2("A Brief History of Western Civilization"); book1.showtitle(); // display book1's title book2.showtitle(); // display book2's title return 0; }

A First Book of C++ 4th Edition19 Pointers as Class Members (cont'd.)

A First Book of C++ 4th Edition20 Assignment Operators and Copy Constructors Reconsidered If a class contains no pointer data members, compiler-supplied defaults work well for assignment operators and copy constructors –Compiler defaults provide member-by-member operation with no adverse side effects –Problems occur with defaults if pointers are involved Example of problem: –Figure 12.9a shows pointers and allocated memory of Program 12.6 before execution

A First Book of C++ 4th Edition21 Assignment Operators and Copy Constructors Reconsidered (cont'd.)

A First Book of C++ 4th Edition22 Assignment Operators and Copy Constructors Reconsidered (cont'd.) Example of problem (cont'd.): –Now insert statement: book 2 = book1; before closing brace of main() Compiler default assignment is used Produces memberwise copy –Address in book1 ’s pointer is copied into book2 ’s pointer –Both pointers now point to same address –Address of A Brief History of Western Civilization is lost (as shown in Figure 12.9b)

A First Book of C++ 4th Edition23 Assignment Operators and Copy Constructors Reconsidered (cont'd.)

A First Book of C++ 4th Edition24 Assignment Operators and Copy Constructors Reconsidered (cont'd.) Example of problem (cont'd.): –Effect of loss of address of: A Brief History of Western Civilization No way for operating system to release this memory (until program terminates) If destructor attempts to release memory pointed to by book2, book1 will point to an undefined memory location Solution to problem: copy book titles and leave pointers alone (as in Figure 12.9c) – Must write our own assignment operator

A First Book of C++ 4th Edition25 Assignment Operators and Copy Constructors Reconsidered (cont'd.)

A First Book of C++ 4th Edition26 Assignment Operators and Copy Constructors Reconsidered (cont'd.) Definition of assignment operator void Book::operator=(Book& oldbook) { if(oldbook.title != NULL) // check that it exists delete(title); // release existing memory title = new char[strlen(oldbook.title) + 1]; // allocate new memory strcpy(title, oldbook.title); // copy the title } Problems associated with assignment operator also exist with default copy constructor –Need to also define a new copy constructor

A First Book of C++ 4th Edition27 Common Programming Errors Attempting to override a virtual function without using the same type and number of arguments as the original function Using the keyword virtual in the class implementation section Forgetting to delete dynamically created objects Attempting to use memberwise assignment between objects containing a pointer member

A First Book of C++ 4th Edition28 Summary Inheritance is the capability of deriving one class from another class Base class functions can be overridden by derived class functions with the same name Polymorphism is the capability of having the same function name invoke different responses In static binding, the determination of which function is called is made at compile time A virtual function designates that dynamic binding should take place

A First Book of C++ 4th Edition29 Summary (cont'd.) Pointers can be included as class data members –Adhere to same rules as pointer variables Copy default constructors and default assignment operators are typically not useful with classes that contain pointer members

A First Book of C++ 4th Edition30 Chapter Supplement: UML Class and Object Diagrams Program modeling –Process of designing an application Unified Modeling Language (UML) –Widely accepted as a technique for developing object-oriented programs –Uses diagrams and techniques that are easy to understand Each item is addressed by separate views and diagrams UML has nine diagram types

A First Book of C++ 4th Edition31 Class and Object Diagrams Class diagrams –Used to describe classes and their relationships Object diagrams –Used to describe objects and their relationships Attributes have two qualities: type and visibility –Type is either a primitive data type or a class data type –Visibility defines where an attribute can be seen: private, public, protected

A First Book of C++ 4th Edition32 Class and Object Diagrams (cont’d.)