static_cast operator: cast base class pointer into derived class pointer : class cast « Class « C++ Tutorial






#include <iostream>
using namespace std;
class BaseClass {
public:
   void f( void ) const { cout << "BASE\n"; }
};

class DerivedClass: public BaseClass {
public:
   void f( void ) const { cout << "DERIVED\n"; }
};

void test( BaseClass * );

int main()
{
   // use static_cast for a conversion
   double d = 8.22;
   int x = static_cast< int >( d );
 
   cout << "d is " << d << "\nx is " << x << endl;

   BaseClass base;  // instantiate base object
   test( &base );   // call test

   return 0;
}
 
void test( BaseClass *basePtr )
{
   DerivedClass *derivedPtr;

   // cast base class pointer into derived class pointer    
   derivedPtr = static_cast< DerivedClass * >( basePtr );
   derivedPtr->f();   // invoke DerivedClass function f
}








9.21.class cast
9.21.1.dynamic_cast from derived to base
9.21.2.static_cast operator: cast base class pointer into derived class pointer
9.21.3.Demonstrating the const_cast operator.
9.21.4.dynamic_cast between base class and subclass