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