POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors

Similar documents
Polymorphism. Problems with switch statement. Solution - use virtual functions (polymorphism) Polymorphism

Object Oriented Software Design II

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

C++ INTERVIEW QUESTIONS

Java Interview Questions and Answers

Multichoice Quetions 1. Atributes a. are listed in the second part of the class box b. its time is preceded by a colon. c. its default value is

Description of Class Mutation Mutation Operators for Java

C++FA 5.1 PRACTICE MID-TERM EXAM

CIS 190: C/C++ Programming. Polymorphism

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

Constructor, Destructor, Accessibility and Virtual Functions

Glossary of Object Oriented Terms

CSCI 253. Object Oriented Programming (OOP) Overview. George Blankenship 1. Object Oriented Design: Java Review OOP George Blankenship.

13 Classes & Objects with Constructors/Destructors

Compile-time type versus run-time type. Consider the parameter to this function:

IS0020 Program Design and Software Tools Midterm, Feb 24, Instruction

The Java Series. Java Essentials I What is Java? Basic Language Constructs. Java Essentials I. What is Java?. Basic Language Constructs Slide 1

Classes and Pointers: Some Peculiarities (cont d.)

1.1.3 Syntax The syntax for creating a derived class is very simple. (You will wish everything else about it were so simple though.

An Incomplete C++ Primer. University of Wyoming MA 5310

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

MAHALAKSHMI ENGINEERING COLLEGE B TIRUCHIRAPALLI

SE 360 Advances in Software Development Object Oriented Development in Java. Polymorphism. Dr. Senem Kumova Metin

Advanced Data Structures

6.088 Intro to C/C++ Day 4: Object-oriented programming in C++ Eunsuk Kang and Jean Yang

Basic Logic Gates. Logic Gates. andgate: accepts two binary inputs x and y, emits x & y. orgate: accepts two binary inputs x and y, emits x y

OpenCL Static C++ Kernel Language Extension

INTRODUCTION TO OBJECTIVE-C CSCI 4448/5448: OBJECT-ORIENTED ANALYSIS & DESIGN LECTURE 12 09/29/2011

C++ Programming Language

Sources: On the Web: Slides will be available on:

Textbook: T. Issariyakul and E. Hossain, Introduction to Network Simulator NS2, Springer

Fundamentals of Java Programming

Introduction to C++ Introduction to C++ Week 7 Dr Alex Martin 2013 Slide 1

C++ Support for Abstract Data Types


C++ Overloading, Constructors, Assignment operator

PHP Object Oriented Classes and objects

CS193j, Stanford Handout #10 OOP 3

explicit class and default definitions revision of SC22/WG21/N1582 = and SC22/WG21/ N

Object Oriented Software Design II

1. Polymorphism in C++...2

Software Engineering 1 EEL5881 Spring Homework - 2

MSP430 C/C++ CODE GENERATION TOOLS Compiler Version 3.2.X Parser Error/Warning/Remark List

J a v a Quiz (Unit 3, Test 0 Practice)

Operator Overloading. Lecture 8. Operator Overloading. Running Example: Complex Numbers. Syntax. What can be overloaded. Syntax -- First Example

C++FA 3.1 OPTIMIZING C++

Lecture 7 Notes: Object-Oriented Programming (OOP) and Inheritance

N3458: Simple Database Integration in C++11

Java Programming Language

CS107L Handout 02 Autumn 2007 October 5, 2007 Copy Constructor and operator=

5 CLASSES CHAPTER. 5.1 Object-Oriented and Procedural Programming. 5.2 Classes and Objects 5.3 Sample Application: A Clock Class

Moving from CS 61A Scheme to CS 61B Java

Part I. Multiple Choice Questions (2 points each):

CEC225 COURSE COMPACT

CS193D Handout 06 Winter 2004 January 26, 2004 Copy Constructor and operator=

Compiler Construction

1 bool operator==(complex a, Complex b) { 2 return a.real()==b.real() 3 && a.imag()==b.imag(); 4 } 1 bool Complex::operator==(Complex b) {

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)

Grundlagen der Betriebssystemprogrammierung

Konzepte objektorientierter Programmierung

Ch 7-1. Object-Oriented Programming and Classes

CS506 Web Design and Development Solved Online Quiz No. 01

An Internet Course in Software Development with C++ for Engineering Students

What is a Loop? Pretest Loops in C++ Types of Loop Testing. Count-controlled loops. Loops can be...

Chapter 5 Functions. Introducing Functions

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON

Chapter 13 - Inheritance

CpSc212 Goddard Notes Chapter 6. Yet More on Classes. We discuss the problems of comparing, copying, passing, outputting, and destructing

C++ Language Tutorial

Computer Programming C++ Classes and Objects 15 th Lecture

Basic Object-Oriented Programming in Java

El Dorado Union High School District Educational Services

Netscape Internet Service Broker for C++ Programmer's Guide. Contents

Regression Test Selection for Java Software

Object-Oriented Programming

Class 16: Function Parameters and Polymorphism

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

Goals for This Lecture:

The C Programming Language course syllabus associate level

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

Java (12 Weeks) Introduction to Java Programming Language

JAVA - METHODS. Method definition consists of a method header and a method body. The same is shown below:

D06 PROGRAMMING with JAVA

Chapter 13 Storage classes

Tutorial on Writing Modular Programs in Scala

Inheritance in Programming Languages

Friendship and Encapsulation in C++

POLYTYPIC PROGRAMMING OR: Programming Language Theory is Helpful

Conditions & Boolean Expressions

LAB4 Making Classes and Objects

History OOP languages Year Language 1967 Simula Smalltalk

Textbook: T. Issariyakul and E. Hossain, Introduction to Network Simulator NS2, Springer

Introduction to Programming Block Tutorial C/C++

Data Structures Using C++ 2E. Chapter 5 Linked Lists

Brent A. Perdue. July 15, 2009

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

AP Computer Science Java Subset

Web development... the server side (of the force)

17. Friendship and Inheritance

AP COMPUTER SCIENCE A 2007 SCORING GUIDELINES

Transcription:

POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors CSC 330 OO Software Design 1

Abstract Base Classes class B { // base class virtual void m( ) { /*... */ } // define m class D1 : public B { // derived class // m could be--but need not be--overridden class D2 : public B { // derived class // m could be--but need not be--overridden CSC 330 OO Software Design 2

Discussions We have a base class B and two derived classes, D1 and D2. The base class has a virtual method m that each derived class can override. Yet the derived classes D1 and D2 are not required to override method m. In object-oriented design, it is sometimes desirable to specify methods that classes such as D1 and D2 should define. CSC 330 OO Software Design 3

Shared Interface Definition: A collection of methods that different classes must define, with each class defining the methods in ways appropriate to it. C++ abstract base class can be used to specify methods that any derived class must define if the class is to have objects instantiate it. An abstract base class thus can be used to specify a shared interface. CSC 330 OO Software Design 4

Abstract Base Classes and Pure Virtual Methods An abstract base class is abstract in that no objects can instantiate it. Such a class can be used to specify virtual methods that any derived class must override in, order to have objects instantiate the derived clas. A class must meet one requirement to be an abstract base class: The class must have a pure virtual method. A pure virtual method is one whose declaration ends with the special syntax =0. CSC 330 OO Software Design 5

EXAMPLE 5.4. 1. class ABC { // Abstract Base Class virtual void open ( ) = 0; The class ABC has a pure virtual method named open. By making open pure virtual, we thereby make ABC an abstract base class. CSC 330 OO Software Design 6

EXAMPLE 5.4.2. class ABC { // Abstract Base Class virtual void open( ) = 0; ABC obj; //***** ERROR: ABC is an abstract class Although an abstract base class cannot have objects instantiate it, such a class can have derived classes. A class derived from an abstract base class must override all of the base class's pure virtual methods; otherwise, the derived class itself becomes abstract and no objects can instantiate the derived class. CSC 330 OO Software Design 7

EXAMPLE 5.4.3. class ABC { // Abstract Base Class virtual void open( ) = 0; class X : public ABC { // 1st derived class virtual void open( ) { /* */ } // override open( ) class Y : public ABC { // 2nd derived class //*** open is not overridden ABC a1; // **** ERROR: ABC is abstract X x1; // **** Ok, X overrides open( ) and is not abstract Y y1 // **** ERROR: Y is abstract open( ) not defined CSC 330 OO Software Design 8

Discussions Class X overrides the pure virtual method inherited from the abstract base class ABC. Therefore, X is not abstract and may have objects instantiate it. By contrast, Y does not override the pure virtual method inherited from ABC. Therefore, Y becomes an abstract base class and cannot have objects instantiate it. One pure virtual method suffices to make a class an abstract base class. An abstract base class may have other methods that are not pure virtual or not even virtual at all. Further, an abstract base class may have data members. An abstract base class's members may be private, protected, or public. CSC 330 OO Software Design 9

EXAMPLE 5.4.4. class ABC { // Abstract Base Class ABC( ) { /* */ } // default constructor ABC( int x ) { /* */ } // general constructor ~ABC( ) { /* */ } // destructor virtual void open( ) = 0 ; // pure virtual virtual void print( ) const { /* */ } // virtual int getcount( ) const { return n; } // nonvirtual private: int n; // data member CSC 330 OO Software Design 10

Discussions ABC remains abstract, however, because it still has the pure virtual method open. Therefore, no objects can instantiate ABC. Any class derived from ABC still must override open if the derived class is not to become abstract itself. However, a derived class can simply use the inherited versions of print and getcount. CSC 330 OO Software Design 11

Restrictions on Pure Functions Only a virtual method can be pure. Neither a nonvirtual nor a toplevel function can be declared pure virtual. EXAMPLE 5.4.5. void f( ) = 0; class C { void open( ) = 0; //***** ERROR: not a virtual method //***** ERROR: not a virtual method CSC 330 OO Software Design 12

Uses of Abstract Base Classes class BasicFile { // Abstract Base Class // methods that any derived class should override virtual void open( ) = 0; virtual void close( ) = 0; virtual void flush( ) = 0; class InFile : public BasicFile { virtual void open( ) { /* */ } // definition virtual void close( ) { /* */ } // definition virtual void flush( ) { /* */ } // definition class OutFile : public BasicFile { virtual void open( ) { /* */ } // definition virtual void close( ) { /* */ } // definition virtual void flush( ) { /* */ } // definition FIGURE 5.4.1 An abstract base class that specifies an interface shared by two derived classes. CSC 330 OO Software Design 13

Run-Time Identification C++ supports run-time type identification (RTTI), which provides mechanisms to Check type conversions at run time. Determine an object's type at run time. Extend the RTTI provided by C++. CSC 330 OO Software Design 14

The dynamic_cast Operator In C++ a legal compile-time cast still may result in a run-time error. This danger may be particularly acute when a cast involves pointers or references to objects. The dynamic_cast operator can be used to test, at run time, when a cast involving objects is problematic. CSC 330 OO Software Design 15

EXAMPLE 5.5.1. class B { //... class D : public B { // int main( ) { /* 1 */ D* p; // pointer to derived class /* 2 */ p = new B; //***** ERROR: explicit cast needed /* 3 */ p = static_cast< D* >( new B ) ; // caution! // } CSC 330 OO Software Design 16

Discussion In general, it is a bad idea for a derived class pointer to point to a base class object. Nonetheless, this can be done with explicit casting. In line 3, we use a static_cast so that p can point to an object of the base class B. The static_cast in Example 5.5.1 is legal but dangerous. In particular, the cast may lead to a run-time error. CSC 330 OO Software Design 17

EXAMPLE 5.5.2. class B { void f( ) { } // Note: no method m class D : public B { void m( ) { } // not in base class int main( ) { D* p; // *** pointer to derived class p = static_cast< D* >( new B ); // caution! p -> m( ) ; // ERROR: there is no B::m! // } CSC 330 OO Software Design 18

Discussions Base class B does not have a method named m. In main, the static_cast again allows p to point to a B object. There is no compile-time error from the method invocation p->m(); because p is of type D* and class D has the required method m. Nonetheless, a run-time error results because p points to a B object-that is, to an object that has no method m. We can summarize the problem illustrated in Example 5.5.2 by saying that the static_cast does not ensure type safety. The cast is not type safe because the method invocation p->m( ); generates a run-time error, although it is syntactically legal. CSC 330 OO Software Design 19

Dynamic cast cont d p's declared data type of D* implies that p can be used to invoke the method D: : m. The problem is that, at run time, p happens to point to a B object, which has no method m. C++ provides the dynamic_cast operator to check, at run time, whether a cast is type safe. A dynamic_cast has the same basic syntax as a staticcast. However, a dynamic_cast is legal only on a polymorphic type, that is, on a class that has at least one virtual method. CSC 330 OO Software Design 20

EXAMPLE 5.5.3. class C { // C has no virtual methods class T { // int main( ) { dynamic_cast< T* >( new C ) ; // *** ERROR // } contains an error because it applies a dynamic_cast to the nonpolymorphic type C. C is nonpolymorphic because it has no virtual methods. CSC 330 OO Software Design 21

Correction class C { virtual void m( ) { } // C is now polymorphic The target type of a dynamic_cast, which is specified in angle brackets, must be a pointer or a reference. If T is a class, then T* and T& are legal targets for a dynamic_cast, but T is not. CSC 330 OO Software Design 22

EXAMPLE 5.5.4. class A { // polymorphic type // A has a virtual method class T { // target class // int main( ) { A a1; dynamic_cast< T >( a1 ) // *** ERROR // } contains an error because the target type is T rather than, for example, T* or T&. CSC 330 OO Software Design 23

EXAMPLE 5.5.5. class B { virtual void f( ) { } // Note: no method m class D : public B { void m( ) { } // not in base class int main( ) { D* p = dynamic_cast< D* > ( new B) ; if ( p ) // is the cast type safe? p->m( ); // if so, invoke p->m( ) else cerr << "Not safe for p to point to a B << endl; // } CSC 330 OO Software Design 24

Discussions We initialize p, of type D*, to the value of a dynamic_cast. If T is a type and ptr is a pointer to a polymorphic type, then the expression dynamic_cast< T* > ( ptr ) evaluates to ptr, if the cast is type safe, and to zero (false), if the cast is not type safe. In our example, the cast source is the expression new B, which evaluates to a non-null address if the new operation succeeds. So p would point to the dynamically allocated B object, if the dynamic_cast expression succeeded. If the cast expression failed, as it does in this case, then p is assigned NULL as its value. The dynamic_cast evaluates to NULL (false) precisely because we are trying to have the derived class pointer p point to the base class object created by new B. By checking the result of the dynamic_cast in the if statement, we avoid the run-time error. CSC 330 OO Software Design 25

Summary of dynamic-cast and static-cast C++ provides different casts for different purposes. A static_cast can be applied to any type, polymorphic or not. A dynamic_cast can be applied only to a polymorphic type, and the target type of a dynamic_cast must be a pointer or a reference. In these respects, a static_cast is more basic and general than a dynamic_cast. However, only a dynamic_cast can be used to check at run time whether a conversion is type safe. In this respect, a dynamic_cast is more powerful than a static_cast. CSC 330 OO Software Design 26

COMMON PROGRAMMING ERRORS 1. It is an error to declare a top-level function virtual: virtual bool f( ); //***** ERROR: f is not a method Only methods can be virtual. 2. It is an error to declare a static method virtual: class C { virtual void m( ) ; // ok, object method virtual static void s( ); //***** ERROR: static method CSC 330 OO Software Design 27

COMMON PROGRAMMING ERRORS cont d 3. If a virtual method is defined outside the class declaration, then the keyword virtual occurs in its declaration but not in its definition: class C { virtual void m1( ) { /*... */ } // ok, decl + def virtual void m2( ); // ok, declaration // *** ERROR: virtual should not occur in a definition // outside the class declaration virtual void C::m2( ) { // } CSC 330 OO Software Design 28

COMMON PROGRAMMING ERRORS cont d 4. It is an error to declare any constructor virtual, although the destructor may be virtual: class C { virtual C( ); // *** ERROR: constructor virtual C( int ) ; //*** ERROR: constructor virtual ~C( ); // ok, destructor CSC 330 OO Software Design 29

COMMON PROGRAMMING ERRORS cont d 5. It is bad programming practice not to delete a dynamically created object before the object is inaccessible: class C { // void f( ) { C* p = new C; // dynamically create a C object // use it } //****** ERROR: should delete the object! Once control exits f, the object to which p points can no longer be accessed. Therefore, storage for this object ought to be freed: void f ( ) { C* p = new C; // dynamically create a C object //... use it delete p; // delete it } CSC 330 OO Software Design 30

COMMON PROGRAMMING ERRORS cont d 6. If a method hides an inherited method, then it is an error to try to invoke the inherited method without using its full name: class A { void m( int ) { /* */ } // takes 1 arg class Z : public A { public; void m( ) { /* */ } // takes 0 args, hides A::m int main( ) { Z z1; z1.m( -999 ) ; // ERROR: Z::m hides A::m z1.a::m( -999 ) // ok, full name z1.m( ); // ok, local method // } The error remains even if m is virtual because A: :m and Z: :m do not have the same signature. CSC 330 OO Software Design 31

COMMON PROGRAMMING ERRORS cont d 7. It is an error to expect run-time binding of nonvirtual methods. In the code segment class A { void m( ) { cout << "A::m" << endl; } class Z : public A { void m( ) { cout << "Z::m, << endl ; } int main( ) { A* p = new Z; // ok, p points to Z object p->m(); // prints A::m, not Z::m // } as m is not virtual. Because compile-time binding is in effect, the call p->m( ); is to A: m since p's data type is A*. It is irrelevant that p happens to point to a Z object. If we make m a virtual method class A { virtual void m( ) { cout << "A::m " << endl; } then the output is Z: :m because run-time binding is in effect and p points to a Z object. CSC 330 OO Software Design 32

COMMON PROGRAMMING ERRORS cont d 8. It is an error to expect a derived class virtual method D : : m to override a base class virtual method B: :m if the two methods have different signatures. The code segment class A { virtual void m( ); class Z : public A { // base class virtual method //***** Caution: Z::m hides A::m virtual void m( int ) ; // derived class virtual method has two virtual methods named m, but Z: :m does not override A: :m because the two methods have different signatures. For useful polymorphism to occur, the virtual methods must have the same signature, not just the same name. In this example, the two virtual methods are completely unrelated. They simply happen to share a name. CSC 330 OO Software Design 33

COMMON PROGRAMMING ERRORS cont d 9. It is an error to try to define objects that instantiate an abstract base class: class ABC { // abstract base class virtual void m( ) = 0; // pure virtual method ABC a1; //***** ERROR: ABC is abstract 10. If a class C is derived from an abstract base class ABC and C does not override all of ABC's pure virtual methods, then C is abstract and cannot have objects instantiate it: class ABC { // abstract base class virtual void m1( ) = 0; // pure virtual method virtual void m2( ) = 0; // pure virtual method class C : public ABC { virtual void m1( ) { /* */ } // override m1 // m2 not overridden C c1; //***** ERROR: C is abstract CSC 330 OO Software Design 34

COMMON PROGRAMMING ERRORS cont d 11. A dynamic-cast may be applied only to a polymorphic type, that is, a class with at least one virtual method. Therefore, the following code segment is in error: class C { //... no virtual methods int main( ) { //***** ERROR: C is not polymorphic dynamic_cast< void* >( new C ) ; // } CSC 330 OO Software Design 35

COMMON PROGRAMMING ERRORS cont d 12. The target type of a dynamic_cast (that is, the expression in angle brackets) must be a pointer or a reference. Therefore, the following code segment is in error: class C { virtual void m( ) { } class A { // int main( ) { C c1; //***** ERROR: target type must a pointer or reference A a1 = dynamic_cast< A >( c1 ) ; // } CSC 330 OO Software Design 36