Absolute C++ (phần 17) pps

40 310 0
Absolute C++ (phần 17) pps

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

640 Polymorphism and Virtual Functions Self-Test Exercises 3. Is it legal to have an abstract class in which all member functions are pure virtual functions? 4. Given the definition of the class Employee in Display 15.6, which of the following are legal? a. Employee joe; joe = Employee( ); b. class HourlyEmployee : public Employee { public: HourlyEmployee( ); < Some more legal member function definitions, none of which are pure virtual functions. > private: double wageRate; double hours; }; int main( ) { Employee joe; joe = HourlyEmployee( ); c. bool isBossOf(const Employee& e1, const Employee& e2); Display 15.6 Interface for the Abstract Class Employee (part 2 of 2) 25 double netPay; 26 }; 27 }//SavitchEmployees 28 #endif //EMPLOYEE_H Pointers and Virtual Functions 641 Pointers and Virtual Functions Beware lest you lose the substance by grasping at the shadow. Aesop, The Dog and the Shadow This section explores some of the more subtle points about virtual functions. To understand this material, you need to have covered the material on pointers given in Chapter 10. ■ VIRTUAL FUNCTIONS AND EXTENDED TYPE COMPATIBILITY If Derived is a derived class of the base class Base, then you can assign an object of type Derived to a variable (or parameter) of type Base, but not the other way around. If you consider a concrete example, this becomes sensible. For example, DiscountSale is a derived class of Sale (Displays 15.1 and 15.3). You can assign an object of the class DiscountSale to a variable of type Sale, since a DiscountSale is a Sale. However, you cannot do the reverse assignment, since a Sale is not necessarily a DiscountSale. The fact that you can assign an object of a derived class to a variable (or parameter) of its base class is critically important for reuse of code via inheritance. However, it does have its problems. For example, suppose a program or unit contains the following class definitions: class Pet { public: string name; virtual void print( ) const; }; class Dog : public Pet { public: string breed; virtual void print( ) const; //keyword virtual not needed, //but put here for clarity. }; Dog vdog; Pet vpet; Now concentrate on the data members, name and breed. (To keep this example simple, we have made the member variables public. In a real application, they should be private and have functions to manipulate them.) 15.2 642 Polymorphism and Virtual Functions Anything that is a Dog is also a Pet. It would seem to make sense to allow programs to consider values of type Dog to also be values of type Pet, and hence the following should be allowed: vdog.name = "Tiny"; vdog.breed = "Great Dane"; vpet = vdog; C++ does allow this sort of assignment. You may assign a value, such as the value of vdog, to a variable of a parent type, such as vpet, but you are not allowed to perform the reverse assignment. Although the above assignment is allowed, the value that is assigned to the variable vpet loses its breed field. This is called the slicing problem. The following attempted access will produce an error message: cout << vpet.breed; // Illegal: class Pet has no member named breed You can argue that this makes sense, since once a Dog is moved to a variable of type Pet it should be treated like any other Pet and not have properties peculiar to Dogs. This makes for a lively philosophical debate, but it usually just makes for a nuisance when programming. The dog named Tiny is still a Great Dane and we would like to refer to its breed, even if we treated it as a Pet someplace along the way. Fortunately, C++ does offer us a way to treat a Dog as a Pet without throwing away the name of the breed. To do this, we use pointers to dynamic variables. Suppose we add the following declarations: Pet *ppet; Dog *pdog; If we use pointers and dynamic variables, we can treat Tiny as a Pet without losing his breed. The following is allowed. 1 pdog = new Dog; pdog->name = "Tiny"; pdog->breed = "Great Dane"; ppet = pdog; Moreover, we can still access the breed field of the node pointed to by ppet. Suppose that Dog::print( ) const; has been defined as follows: void Dog::print( ) const { 1 If you are not familiar with the -> operator, see the subsection of Chapter 10 entitled “The -> Operator.” slicing problem Pointers and Virtual Functions 643 cout << "name: " << name << endl; cout << "breed: " << breed << endl; } The statement ppet->print( ); will cause the following to be printed on the screen: name: Tiny breed: Great Dane This nice ouput happens by virtue of the fact that print( ) is a virtual member func- tion. (No pun intended.) We have included test code in Display 15.7. Display 15.7 Defeating the Slicing Problem ( part 1 of 2 ) 1 //Program to illustrate use of a virtual function to defeat the slicing 2 //problem. 3 #include <string> 4 #include <iostream> 5 using std::string; 6 using std::cout; 7 using std::endl; 8 class Pet 9 { 10 public: 11 string name; 12 virtual void print( ) const; 13 }; 14 class Dog : public Pet 15 { 16 public: 17 string breed; 18 virtual void print( ) const; 19 }; 20 int main( ) 21 { 22 Dog vdog; 23 Pet vpet; 24 vdog.name = "Tiny"; 25 vdog.breed = "Great Dane"; 26 vpet = vdog; 27 cout << "The slicing problem:\n"; We have made the member variables public to keep the example simple. In a real application they should be private and accessed via member functions. Keyword virtual is not needed here, but we put it here for clarity. 644 Polymorphism and Virtual Functions Display 15.7 Defeating the Slicing Problem ( part 2 of 2 ) 28 //vpet.breed; is illegal since class Pet has no member named breed. 29 vpet.print( ); 30 cout << "Note that it was print from Pet that was invoked.\n"; 31 cout << "The slicing problem defeated:\n"; 32 Pet *ppet; 33 ppet = new Pet; 34 Dog *pdog; 35 pdog = new Dog; 36 pdog->name = "Tiny"; 37 pdog->breed = "Great Dane"; 38 ppet = pdog; 39 ppet->print( ); 40 pdog->print( ); 41 //The following, which accesses member variables directly 42 //rather than via virtual functions, would produce an error: 43 //cout << "name: " << ppet->name << " breed: " 44 // << ppet->breed << endl; 45 //It generates an error message saying 46 //class Pet has no member named breed. 47 return 0; 48 } 49 void Dog::print( ) const 50 { 51 cout << "name: " << name << endl; 52 cout << "breed: " << breed << endl; 53 } 54 void Pet::print( ) const 55 { 56 cout << "name: " << name << endl; 57 } S AMPLE D IALOGUE The slicing problem: name: Tiny Note that it was print from Pet that was invoked. The slicing problem defeated: name: Tiny breed: Great Dane name: Tiny breed: Great Dane These two print the same output: name: Tiny breed: Great Dane Note that no breed is mentioned Pointers and Virtual Functions 645 Pitfall Object-oriented programming with dynamic variables is a very different way of viewing programming. This can all be bewildering at first. It will help if you keep two simple rules in mind: 1. If the domain type of the pointer pAncestor is an ancestor class for the domain type of the pointer pDescendant, then the following assignment of pointers is allowed: pAncestor = pDescendant; Moreover, none of the data members or member functions of the dynamic variable being pointed to by pDescendant will be lost. 2. Although all the extra fields of the dynamic variable are there, you will need virtual member functions to access them. T HE S LICING P ROBLEM Although it is legal to assign a derived class object to a base class variable, assigning a derived class object to a base class object slices off data. Any data members in the derived class object that are not also in the base class will be lost in the assignment, and any member functions that are not defined in the base class are similarly unavailable to the resulting base class object. For example, if Dog is a derived class of Pet, then the following is legal: Dog vdog; Pet vpet; vpet = vdog; However, vpet cannot be a calling object for a member function from Dog unless the function is also a member function of Pet, and all the member variables of vdog that are not inherited from the class Pet are lost. This is the slicing problem. Note that simply making a member function virtual does not defeat the slicing problem. Note the following code from Display 15.7: Dog vdog; Pet vpet; vdog.name = "Tiny"; vdog.breed = "Great Dane"; vpet = vdog; . . . vpet.print( ); Although the object in vdog is of type Dog, when vdog is assigned to the variable vpet (of type Pet) it becomes an object of type Pet. So, vpet.print( ) invokes the version of print( ) defined in Pet, not the version defined in Dog. This happens despite the fact that print( ) is virtual. In order to defeat the slicing problem, the function must be virtual and you must use pointers and dynamic variables. 646 Polymorphism and Virtual Functions Tip Self-Test Exercises 5. Why can’t you assign a base class object to a derived class variable? 6. What is the problem with the (legal) assignment of a derived class object to a base class variable? 7. Suppose the base class and the derived class each has a member function with the same sig- nature. When you have a base class pointer to a derived class object and call a function member through the pointer, discuss what determines which function is actually called, the base class member function or the derived class member function. M AKE D ESTRUCTORS V IRTUAL It is a good policy to always make destructors virtual, but before we explain why this is a good policy we need to say a word or two about how destructors and pointers interact and about what it means for a destructor to be virtual. Consider the following code, where SomeClass is a class with a destructor that is not virtual: SomeClass *p = new SomeClass; . . . delete p; When delete is invoked with p, the destructor of the class SomeClass is automatically invoked. Now, let’s see what happens when a destructor is marked virtual. The easiest way to describe how destructors interact with the virtual function mechanism is that destructors are treated as if all destructors had the same name (even though they do not really have the same name). For example, suppose Derived is a derived class of the class Base and suppose the destructor in the class Base is marked virtual. Now consider the following code: Base *pBase = new Derived; . . . delete pBase; When delete is invoked with pBase, a destructor is called. Since the destructor in the class Base was marked virtual and the object pointed to is of type Derived, the destructor for the class Derived is called (and it in turn calls the destructor for the class Base). If the destructor in the class Base had not been declared as virtual, then only the destructor in the class Base would be called. Another point to keep in mind is that when a destructor is marked virtual, then all destructors of derived classes are automatically virtual (whether or not they are marked virtual). Again, this behavior is as if all destructors had the same name (even though they do not). Now we are ready to explain why all destructors should be virtual. Consider what happens when destructors are not declared as virtual in a base class. In particular consider the base class PFArrayD Pointers and Virtual Functions 647 (partially filled array of doubles) and its derived class PFArrayDBak (partially filled array of doubles with backup). We discussed these classes in Chapter 14. That was before we knew about virtual functions, and so the destructor in the base class PFArrayD was not marked virtual. In Display 15.8 we have summarized all the facts we need about the classes PFArrayD and PFArrayDBak so that you need not look back to Chapter 14. Consider the following code: PFArrayD *p = new PFArrayDBak; . . . delete p; Since the destructor in the base class is not marked virtual, only the destructor for the base class ( PFArrayD) will be invoked. This will return the memory for the member array a (declared in PFArrayD) to the freestore, but the memory for the member array b (declared in PFArrayD- Bak ) will never be returned to the freestore (until the program ends). On the other hand, if (unlike Display 15.8) the destructor for the base class PFArrayD were marked virtual, then when delete is applied to p, the constructor for the class PFArrayDBak would be invoked (since the object pointed to is of type PFArrayDBak). The destructor for the class PFArrayDBak would delete the array b and then automatically invoke the constructor for the base class PFArrayD, and that would delete the member array a. So, with the base class destructor marked as virtual, all the memory is returned to the freestore. To prepare for eventual- ities such as these, it is best to always mark destructors as virtual. ■ DOWNCASTING AND UPCASTING You might think some sort of type casting would allow you to easily get around the slic- ing problem. However, things are not that simple. The following is illegal: Pet vpet; Dog vdog; //Dog is a derived class with base class Pet. . . . vdog = static_cast<Dog>(vpet); //ILLEGAL! However, casting in the other direction is perfectly legal and does not even need a cast- ing operator: vpet = vdog; //Legal (but does produce the slicing problem.) Casting from a descendant type to an ancestor type is known as upcasting, since you are moving up the class hierarchy. Upcasting is safe because you are simply disre- garding some information (disregarding member variables and functions). So, the fol- lowing is perfectly safe: vpet = vdog; upcasting 648 Polymorphism and Virtual Functions Display 15.8 Review of the Classes PFArrayD and PFArrayDBak class PFArrayD { public: PFArrayD( ); . . . ~PFArrayD( ); protected: double *a; //for an array of doubles. int capacity; //for the size of the array. int used; //for the number of array positions currently in use. }; PFArrayD::PFArrayD( ) : capacity(50), used(0) { a = new double[capacity]; } PFArrayD::~PFArrayD( ) { delete [] a; } class PFArrayDBak : public PFArrayD { public: PFArrayDBak( ); . . . ~PFArrayDBak( ); private: double *b; //for a backup of main array. int usedB; //backup for inherited member variable used. }; PFArrayDBak::PFArrayDBak( ) : PFArrayD( ), usedB(0) { b = new double[capacity]; } PFArrayDBak::~PFArrayDBak( ) { delete [] b; } The destructors should be virtual, but we had not yet covered virtual functions when we wrote these classes. Some details about the derived class PFArrayDBak. A complete definition of PFArrayDBak is given in Displays 14.10 and 14.11, but this display has all the details you need for this chapter. Some details about the base class PFArrayD. A more complete definition of PFArrayD is given in Displays 14.8 and 14.9, but this display has all the details you need for this chapter. Pointers and Virtual Functions 649 Casting from an ancestor type to a descended type is called downcasting and is very dangerous, since you are assuming that information is being added (added member variables and functions). The dynamic_cast that we discussed briefly in Chapter 1 is used for downcasting. It is of some possible use in defeating the slicing problem but is dangerously unreliable and fraught with pitfalls. A dynamic_cast may allow you to downcast, but it only works for pointer types, as in the following: Pet *ppet; ppet = new Dog; Dog *pdog = dynamic_cast<Dog*>(ppet); //Dangerous! We have had downcasting fail even in situations as simple as this, and so we do not rec- ommend it. The dynamic_cast is supposed to inform you if it fails. If the cast fails, the dynamic_cast should return NULL (which is really the integer 0). 2 If you want to try downcasting keep the following points in mind: 1. You need to keep track of things so that you know the information to be added is indeed present. 2. Your member functions must be virtual, since dynamic_cast uses the virtual func- tion information to perform the cast. ■ HOW C++ IMPLEMENTS VIRTUAL FUNCTIONS You need not know how a compiler works in order to use it. That is the principle of information hiding, which is basic to all good program design philosophies. In particu- lar, you need not know how virtual functions are implemented in order to use virtual functions. However, many people find that a concrete model of the implementation helps their understanding, and when reading about virtual functions in other books you are likely to encounter references to the implementation of virtual functions. So, we will give a brief outline of how they are implemented. All compilers for all languages (including C++) that have virtual functions typically implement them in basically the same way. If a class has one or more member functions that are virtual, the compiler creates what is called a virtual function table for that class. This table has a pointer (memory address) for each virtual member function. The pointer points to the location of the correct code for that member function. If one virtual function was inherited and not changed, then its table entry points to the definition for that function that was given in the parent class (or other ancestor class if need be). If another virtual function had a new definition in the class, then the pointer in the table for that member function points to that definition. (Remember that the property of being a virtual function is 2 The standard says “The value of a failed cast to pointer type is the null pointer of the required result type. A failed cast to a reference type throws a bad_cast.” downcasting virtual function table [...]... function declaration that explains this restriction 2 We have used three kinds of absolute value function: abs, labs, and fabs These functions differ only in the type of their argument It might be better to have a function template for the absolute value function Give a function template for an absolute value function called absolute The template will apply only to types for which < is defined, for which... the parameter T? Choose from the answers listed below a T must be a class b T must not be a class c T can be only a type built into the C++ language d T can be any type, whether built into C++ or defined by the programmer e T can be any kind of type, whether built into C++ or defined by the programmer, but T does have some requirements that must be met (What are they?) 16_CH16.fm Page 660 Monday, August... which the constant 0 can be used in a comparison with a value of that type Thus, the function absolute can be called with any of the number types, such as int, long, and double Give both the function declaration and the function definition for the template 3 Define or characterize the template facility for C++ 4 In the template prefix template what kind of variable is the parameter T? Choose... able to express this more general algorithm in C++ This is a very simple example of algorithm abstraction When we say we are using algorithm abstraction, we mean that we are expressing our algorithms in a very general way so that we can ignore incidental detail and concentrate on the substantive part of the algorithm Function templates are one feature of C++ that supports algorithm abstraction 16_CH16.fm... PM 658 Templates time the arguments are of type int, and the other time the arguments are of type char Consider the following function call from Display 16.1: swapValues(integer1, integer2); When the C++ compiler gets to this function call, it notices the types of the arguments— in this case, int—and then it uses the template to produce a function definition with the type parameter T replaced with the... differently; you should ask a local expert about the details In the function template in Display 16.1 we used the letter T as the parameter for the type This is traditional but is not required by the C++ language The type parameter can be any identifier (other than a keyword) T is a good name for the type parameter, but other names can be used It is possible to have function templates that have more... compilation of templates, so you may need to include your template definition with your code that uses it As usual, at least the function declaration must precede any use of the function template Some C++ compilers have additional special requirements for using templates If you have trouble compiling your templates, check your manuals or check with a local expert You may need to set special options... base class Pet vdog = static_cast(vpet); //ILLEGAL! Chapter Summary s s s s s Late binding means that the decision of which version of a member function is appropriate is decided at runtime In C++, member functions that use late binding are called virtual functions Polymorphism is another word for late binding A pure virtual function is a member function that has no definition A pure virtual... Aristotle is mortal All X’s are Y Z is an X Therefore, Z is Y All cats are mischievous Garfield is a cat Therefore, Garfield is mischievous A Short Lesson on Syllogisms INTRODUCTION This chapter discusses C++ templates, which allow you to define functions and classes that have parameters for type names This enables you to design functions that can be used with arguments of different types and to define classes... not essential to the material presented It is possible to read Section 16.3 ignoring (or even omitting) all occurrences of the keyword virtual 16.1 Function Templates Many of our previously discussed C++ function definitions have an underlying algorithm that is much more general than the algorithm we gave in the function definition For example, consider the function swapValues, which we first discussed . only a type built into the C++ language. d. T can be any type, whether built into C++ or defined by the programmer. e. T can be any kind of type, whether built into C++ or defined by the programmer,. function tem- plate for the absolute value function. Give a function template for an absolute value function called absolute. The template will apply only to types for which < is defined, for. three kinds of absolute value function: abs, labs, and fabs. These func- tions differ only in the type of their argument. It might be better to have a function tem- plate for the absolute value

Ngày đăng: 07/07/2014, 05:20

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan