Topic : Casting in C++
Author : G. Bowden Wise
Page : << Previous 3  
Go to page :


   {
   public:
     // ...
     void computeInterest();
   }
   class MMAcct : public BankAcct
   {
   public:
     // ...
     void computeInterest();
   }
We can now compute interest for an array of BankAcct*s:
   void DoInterest (BankAcct* a[],
                    int num_accts)
   {
     for (int i = 0; i < num_accts; i++)
     {
       // Check for savings
       SavingsAcct* sa =
       dynamic_cast<SavingsAcct*>(accts[i]);
       if (sa)
       {
          sa->creditInterest();
       }

       MMAcct* mm =
       dynamic_cast<MMAcct*>(accts[i]);
       if (mm)
       {
          mm->creditInterest();
       }
     }
   }


A dynamic_cast will return a null pointer if the cast is not successful. So only if the pointer is of type SavingsAcct* or MMAcct* is interest credited. dynamic_cast allows you to perform safe type conversions and let's your programs take appropriate actions when such casts fail.
When a pointer is converted to a void*, the resulting object points to the most derived object in the class hierarchy. This enables the object to be seen as raw memory. Meyers [3] demonstrates how a cast to void* can be used to determine if a particular object is on the heap.


The reinterpret_cast Operator

The reinterpret_cast operator takes the form

   reinterpret_cast<T> (expr)
and is used to perform conversions between two unrelated types. The result of the conversion is usually implementation dependent and, therefore, not likely to be portable. You should use this type of cast only when absolutely necessary.
A reinterpret_cast can also be used to convert a pointer to an integral type. If the integral type is then converted back to the same pointer type, the result will be the same value as the original pointer.

Meyers [3] shows how reinterpret_casts can be used to cast between function pointer types.


Summary

The new C++ cast operators enable you to develop programs which are easier to maintain, understand, and perform some conversions safely. Casts should not be taken lightly. As you convert your old C-style casts to use the new C++ casting operators ask yourself if a cast is really needed here. It may be that you are using a class hierarchy in a way not originally intended or that you may be able to do the same thing with virtual functions.



References

1
ELLIS, M. A., AND STROUSTRUP, B. The Annotated C++ Reference Manual. Addison-Wesley, Reading, Mass., 1990.

2
MEYERS, S. Effective C++: 50 Specific Ways to Improve Your Programs and Designs. Addison-Wesley, Reading, Mass., 1992.

3
MEYERS, S. More Effective C++: 35 New Ways to Improve Your Programs and Designs. Addison-Wesley, Reading, Mass., 1996.

4
STROUSTRUP, B. The Design and Evolution of C++. Addison-Wesley, New York, 1994.



Bowden Wise
Wed Jul 17 13:59:18 EDT 1996


Page : << Previous 3