CSCI-383 Object-Oriented Programming & Design Lecture 18.

Slides:



Advertisements
Similar presentations
Constructors: Access Considerations DerivedClass::DerivedClass( int iR, float fVar) : BaseClass(fVar) { m_uiRating = uiR; } Alternatively DerivedClass::DerivedClass(
Advertisements

Python Objects and Classes
Object Oriented Programming COP3330 / CGS5409.  C++ Automatics ◦ Copy constructor () ◦ Assignment operator =  Shallow copy vs. Deep copy  DMA Review.
Chapter 1 OO using C++. Abstract Data Types Before we begin we should know how to accomplish the goal of the program We should know all the input and.
Rossella Lau Lecture 8, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 8: Polymorphism & C++ pointer  Inheritance.
Chapter 14: Overloading and Templates C++ Programming: Program Design Including Data Structures, Fifth Edition.
Chapter 14: Overloading and Templates
Polymorphism, Virtual Methods and Abstract Classes.
Lecture 12 Destructors “Absolute C++” Chapters 10.3, 15.2.
Rossella Lau Lecture 8, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 8: Polymorphism & C++ pointer  Inheritance.
Chapter 15: Operator Overloading
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.
1 Chapter 14-2 Object- Oriented Software Development Dale/Weems.
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
Lecture 22 Miscellaneous Topics 4 + Memory Allocation.
1 Data Structures - CSCI 102 CS102 C++ Polymorphism Prof Tejada.
1 Virtual Functions and Polymorphism Chapter What You Will Learn What is polymorphism? How to declare and use virtual functions for abstract classes.
Pointer Data Type and Pointer Variables
Learners Support Publications Pointers, Virtual Functions and Polymorphism.
CSE 425: Object-Oriented Programming II Implementation of OO Languages Efficient use of instructions and program storage –E.g., a C++ object is stored.
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.
Polymorphism. Introduction ‘one name multiple forms’ Implemented using overloaded functions and operators Early binding or static binding or static linking.
1 Inheritance We are modeling the operation of a transportation company that uses trains and trucks to transfer goods. A suitable class hierarchy for the.
CSCI-383 Object-Oriented Programming & Design Lecture 14.
CS212: Object Oriented Analysis and Design Lecture 7: Arrays, Pointers and Dynamic Memory Allocation.
Lecture 21 Multiple Inheritance. What is Multiple Inheritance? We defined inheritance earlier in the semester as a relationship between classes. If class.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 13 Introduction to Classes.
Copyright 2004 Scott/Jones Publishing Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 7 Structured Data and Classes.
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.
Lecture 3 Classes, Structs, Enums Passing by reference and value Arrays.
CPSC 252 The Big Three Page 1 The “Big Three” Every class that has data members pointing to dynamically allocated memory must implement these three methods:
OOP using C Abstract data types How to accomplish the task??? Requirements Details Input, output, process Specify each task in terms of input.
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.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 15: Overloading and Templates.
Chapter -6 Polymorphism
Inheritance Initialization & Destruction of Derived Objects Protected Members Non-public Inheritance Virtual Function Implementation Virtual Destructors.
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
More about Java Classes Writing your own Java Classes More about constructors and creating objects.
Overview of C++ Polymorphism
Recap Introduction to Inheritance Inheritance in C++ IS-A Relationship Polymorphism in Inheritance Classes in Inheritance Visibility Rules Constructor.
Polymorphism and Virtual Functions One name many shapes behaviour Unit - 07.
CSCI-383 Object-Oriented Programming & Design Lecture 21.
CSC241 Object-Oriented Programming (OOP) Lecture No. 17.
COP INTERMEDIATE JAVA Inheritance, Polymorphism, Interfaces.
Learners Support Publications Constructors and Destructors.
CPSC 252 ADTs and C++ Classes Page 1 Abstract data types (ADTs) An abstract data type is a user-defined data type that has: private data hidden inside.
Chapter 12: Pointers, Classes, Virtual Functions, Abstract Classes, and Lists.
CSCI-383 Object-Oriented Programming & Design Lecture 17.
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
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.
Class Inheritance Part II: Overriding and Polymorphism Corresponds with Chapter 10.
Constructors and Destructors
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
Class A { public : Int x; A()
Object-Oriented Programming & Design Lecture 18 Martin van Bommel
Inheritance & Polymorphism
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Designing for Inheritance
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes
Introduction to Classes
Constructors and Destructors
9: POLYMORPHISM Programming Technique II (SCSJ1023) Jumail Bin Taliba
Overview of C++ Polymorphism
Presentation transcript:

CSCI-383 Object-Oriented Programming & Design Lecture 18

Virtual Functions  To see more examples of how virtual functions are used, let’s develop another inheritance hierarchy: the base class is timeOfDay, and its derived class is timeOfYear  This hierarchy is illustrated in handout #5handout #5  Both of these classes contain an implementation of the virtual method print

Virtual Functions  Now let’s assume that we are given the following declarations timeOfDay tod(3, 45, 2.2); timeOfYear toy(30, 7, 14, 51.6); timeOfDay* tPtr1 = &tod; timeOfDay* tPtr2 = &toy;  Then the statements tod.print(cout); toy.print(cout); will produce the output 3:45:2.2 30:7:14:51.6

Virtual Functions  Because print is a virtual function, the statements tPtr1->print(cout); tPtr2->print(cout); will also produce the output 3:45:2.2 30:7:14:51.6

Virtual Functions  What would happen if we let the keyword virtual out of the example interfaces?  The statements tPtr1->print(cout); tPtr2->print(cout); would produce the output 3:45:2.2 7:14:51.6

Diversity in the Workspace  One of the ways we can use virtual functions is to create an array of base class pointers and use it as an array of “elements” of diverse types  Could this be done in ANSI C? Certainly! One could create an array of void* elements and point them to instances of various structures  But how would one later know the types of the particular structure instances? Some possibilities include Point at a union of the possible structure types. Then, keep a flag to indicate the structure type of the data currently stored in the union Begin all structures with a flag to indicate its structure type; then, with lots of casting check the flag and treat the block of memory as the appropriate structure type

Diversity in the Workspace  Both of these solutions require the user to keep track of the type of the data. This is unnecessary when one uses virtual functions in C++  The only restriction is that all of the various types would have to be kept in the same inheritance hierarchy  One might even want to define a method named something such as whatTypeAmI that determines the type of an instance for use in conditional statements

Virtual Functions & References  The example in handout #5 also illustrates how one would use virtual functions with reference parametershandout #5 The base class timeOfDay has a friend function, the overloaded operator<< The second parameter of this function is a reference to a base class instance The overloaded operator then calls the appropriate version of print

Virtual Functions & References  For example, using the variables defined in the earlier example, the statements cout << tod << endl; cout << toy << end; will produce the output 3:45:2.2 30:7:14:51.6

Pure Virtual Functions  A class that is too generic to be instantiated is called an abstract class  Some methods might be identified in an abstract class, but not implemented in that class  A C++ method that is identified, but not implemented in a base class is called a pure virtual function

Pure Virtual Functions  A pure virtual function generally has a NULL implementation. For example virtual void print(ostream& cout) = 0;  This NULL implementation is located in the interface of the class  The declaration of a pure virtual function in a class forces the class to be an abstract class  If a pure virtual function declared in a base class is not implemented in a derived class, then the derived class is an abstract class too

Constructors Can’t Be Virtual  Constructors aren’t inherited and can’t be virtual  Constructors are very tightly bound up with a class and each class has its own unique set of constructors  It is non-sensical to declare a constructor virtual since a constructor is always called by name (e.g., ( timeOfDay(...), timeOfYear(...) ) so there is no choice about which version to invoke timeOfYear& timeOfYear::operator=(const timeOfYear& t){ if(this != &t) { timeOfDay::operator=(t); // do rest of timeOfYear copying here } return *this; }

operator= is not inherited either  This method is also very tightly coupled with a class  Remember that, just like with constructors, if you don’t provide an overloading of operator=, a default one is automatically provided  If you choose to implement your own version, you should invoke the parent class to do the parent’s part of the assignment

Virtual Destructors  Normally, when one deletes an instance of a derived class (e.g., timeOfYear ), the destructors of the derived class and those of all the ancestor classes are executed (in this case, the timeOfDay destructor)  But let’s assume that we are given the following statement timeOfDay* tPtr1 = new timeOfYear(30,7,14,51.6);  What happens when one executes the following statement? delete tPtr1;

Virtual Destructors  Since the classes involved in the example do not have virtual destructors, only the timeOfDay destructor is executed!  Further, if additional classes appeared in the hierarchy between timeOfYear and timeOfDay, their destructors would not be executed, either  This behavior can lead to memory leaks and other unpleasantries, especially when dynamic memory or class variables are managed by the derived class  A solution to the problem is the use of virtual destructors

Virtual Destructors  A virtual destructor is simply a destructor that is declared as a virtual function  If the destructor of a base class is declared as virtual, then the destructors of all its descendant classes become virtual, too (even though they do not have the same names)

Virtual Destructors  In the example illustrated in handout #5, the derived class maintains a class variable that is used as an instance counter. The statementhandout #5 timeOfDay* tPtr1 = new timeOfYear(30,7,14,51.6); executes the constructors of timeOfDay and then timeOfYear, thus incrementing the class variable  However, the statement delete tPtr1; executes only the destructor of timeOfDay  Thus, the class variable does not get decremented

Virtual Destructors  Rules of thumb for virtual destructors If any class in a hierarchy manages class variables or dynamic memory, make its destructor virtual If none of the classes in a hierarchy have user- defined destructors, do not use virtual destructors

Pure Virtual Destructors  Ass odd as it may seem, there are times when one may want to define a pure virtual destructor. Why?  One may want to force a class to be an abstract class though it has no pure virtual functions. A pure virtual destructor will do this  It also could be the case that the class is already an abstract class, but one wants to assure that the destructors in the hierarchy are virtual

Pure Virtual Destructors  As one might expect, a pure virtual destructor for class timeOfDay would be declared as follows in the class interface virtual ~timeOfDay(void) = 0;  However, unlike other pure virtual functions, one also must provide an empty implementation for pure virtual destructors timeOfDay::~timeOfDay(void){ }

Virtual Functions: Hidden Details  Instances of classes that have virtual functions must retain “behind the scenes” data to identify the class to which they belong. This information is used to look up appropriate method implementations at run time  In C++, this data consists of a vtbl (virtual function table) pointer. The vtbl pointer points to an array of vptr (virtual function pointer) values (one sometimes sees the word functor used as a synonym for function pointer)  Thus, when one defines virtual functions in a class, space and time overhead is incurred