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

Similar documents
POLYMORPHISM 2 PART. Shared Interface. Discussions. Abstract Base Classes. Abstract Base Classes and Pure Virtual Methods EXAMPLE

C++ Programming: Polymorphism

Polymorphism. Zimmer CSCI 330

What is Polymorphism? Quotes from Deitel & Deitel s. Why polymorphism? How? How? Polymorphism Part 1

Polymorphism Part 1 1

C++ Crash Kurs. Polymorphism. Dr. Dennis Pfisterer Institut für Telematik, Universität zu Lübeck

Increases Program Structure which results in greater reliability. Polymorphism

VIRTUAL FUNCTIONS Chapter 10

COMP322 - Introduction to C++ Lecture 09 - Inheritance continued

CS105 C++ Lecture 7. More on Classes, Inheritance

Cpt S 122 Data Structures. Course Review Midterm Exam # 2

Polymorphism. Miri Ben-Nissan (Kopel) Miri Kopel, Bar-Ilan University

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

A <Basic> C++ Course

Intro to OOP Visibility/protection levels and constructors Friend, convert constructor, destructor Operator overloading a<=b a.

Inheritance, and Polymorphism.

Programming C++ Lecture 5. Howest, Fall 2013 Instructor: Dr. Jennifer B. Sartor

QUIZ. Write the following for the class Bar: Default constructor Constructor Copy-constructor Overloaded assignment oper. Is a destructor needed?

Chapter 5 Object-Oriented Programming

C++ without Classes. CMSC433, Fall 2001 Programming Language Technology and Paradigms. More C++ without Classes. Project 1. new/delete.

Short Notes of CS201

CS201 - Introduction to Programming Glossary By

CS11 Introduction to C++ Fall Lecture 7

Introduction to RTTI. Jonathan Hoyle Eastman Kodak 11/30/00

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe

COMP322 - Introduction to C++

OOPS Viva Questions. Object is termed as an instance of a class, and it has its own state, behavior and identity.

04-24/26 Discussion Notes

Polymorphism. Contents. Assignment to Derived Class Object. Assignment to Base Class Object

CS3157: Advanced Programming. Outline

Inheritance, Polymorphism and the Object Memory Model

Fast Introduction to Object Oriented Programming and C++

Extending Classes (contd.) (Chapter 15) Questions:

Instantiation of Template class

COMP322 - Introduction to C++ Lecture 10 - Overloading Operators and Exceptions

CS OBJECT ORIENTED PROGRAMMING

OBJECT ORIENTED PROGRAMMING USING C++

Passing arguments to functions by. const member functions const arguments to a function. Function overloading and overriding Templates

JAYARAM COLLEGE OF ENGINEERING AND TECHNOLOGY Pagalavadi, Tiruchirappalli (An approved by AICTE and Affiliated to Anna University)

Tokens, Expressions and Control Structures

Object Oriented Programming. Solved MCQs - Part 2

Note 12/1/ Review of Inheritance Practice: Please write down 10 most important facts you know about inheritance...

엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED

C++_ MARKS 40 MIN

What does it mean by information hiding? What are the advantages of it? {5 Marks}

CS32 - Week 4. Umut Oztok. Jul 15, Umut Oztok CS32 - Week 4

Chapter 2. Procedural Programming

OBJ. ORI.& MULT. PROG., M.C.Q. BANK, FOR UNIT -2, SECOND YEAR COMP. ENGG. SEM-4, 2012 PATTERN, U.O.P. UNIT-2

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

Jayaram college of Engineering and Technology, Pagalavadi. CS2203 Object Oriented Programming Question Bank Prepared By: S.Gopalakrishnan, Lecturer/IT

Function Overloading

Polymorphism. Arizona State University 1

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

Inheritance. Program construction in C++ for Scientific Computing. School of Engineering Sciences. Introduction. Michael Hanke.

Inheritance. OOP components. Another Example. Is a Vs Has a. Virtual Destructor rule. Virtual Functions 4/13/2017

Chapter 5. Object- Oriented Programming Part I

Dynamic Binding C++ Douglas C. Schmidt

COEN244: Polymorphism

The Foundation of C++: The C Subset An Overview of C p. 3 The Origins and History of C p. 4 C Is a Middle-Level Language p. 5 C Is a Structured

Object Oriented Software Design II

CS201- Introduction to Programming Current Quizzes

Object-Oriented Programming, Iouliia Skliarova

CS-202 Introduction to Object Oriented Programming

COMP6771 Advanced C++ Programming

(12-1) OOP: Polymorphism in C++ D & D Chapter 12. Instructor - Andrew S. O Fallon CptS 122 (April 3, 2019) Washington State University

Object Oriented Software Design II

Inheritance. Chapter 15 & additional topics

C++ Memory Map. A pointer is a variable that holds a memory address, usually the location of another variable in memory.

C++ Important Questions with Answers

Extending Classes (contd.) (Chapter 15) Questions:

Objectives. INHERITANCE - Part 1. Using inheritance to promote software reusability. OOP Major Capabilities. When using Inheritance?

INHERITANCE - Part 1. CSC 330 OO Software Design 1

Lecture 8: Object-Oriented Programming (OOP) EE3490E: Programming S1 2017/2018 Dr. Đào Trung Kiên Hanoi Univ. of Science and Technology

Written by John Bell for CS 342, Spring 2018

Programming 2. Object Oriented Programming. Daniel POP

CS 251 INTERMEDIATE SOFTWARE DESIGN SPRING C ++ Basics Review part 2 Auto pointer, templates, STL algorithms

These new operators are intended to remove some of the holes in the C type system introduced by the old C-style casts.

1/29/2011 AUTO POINTER (AUTO_PTR) INTERMEDIATE SOFTWARE DESIGN SPRING delete ptr might not happen memory leak!

Rules and syntax for inheritance. The boring stuff

Inheritance and Polymorphism

C++ Inheritance and Encapsulation

Hierarchical inheritance: Contains one base class and multiple derived classes of the same base class.

Paytm Programming Sample paper: 1) A copy constructor is called. a. when an object is returned by value

Suppose we find the following function in a file: int Abc::xyz(int z) { return 2 * z + 1; }

Lecture 5: Inheritance

Preface to the Second Edition Preface to the First Edition Brief Contents Introduction to C++ p. 1 A Review of Structures p.

Inheritance and aggregation

Object-Oriented Concept

Introduction to C++ Systems Programming

Practice for Chapter 11

UNIT - IV INHERITANCE AND FORMATTED I/O

Inheritance and Polymorphism

Introduction to Programming Using Java (98-388)

CPSC 427: Object-Oriented Programming

Chapter 10 Object-Oriented Programming

Lecture-5. Miscellaneous topics Templates. W3101: Programming Languages C++ Ramana Isukapalli

The mechanism that allows us to extend the definition of a class without making any physical changes to the existing class is called inheritance.

Inheritance. Chapter 15 & additional topics

IS 0020 Program Design and Software Tools

Object-Oriented Programming (OOP) Fundamental Principles of OOP

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( ) =0; // pure virtual function 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 pure 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 redefine. 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