Demonstrating the const_cast operator. : class cast « Class « C++ Tutorial






#include <iostream>
using namespace std;
class ConstCastTest {
public:
   void setNumber( int );
   int getNumber() const;
   void printNumber() const;
private:
   int number;
};

void ConstCastTest::setNumber( int num ) { number = num; }

int ConstCastTest::getNumber() const { return number; }

void ConstCastTest::printNumber() const
{
   const_cast< ConstCastTest * >( this )->number--;
   cout << number << endl;
}

int main()
{
   ConstCastTest x;
   x.setNumber( 8 );
   
   cout << "Initial value of number: " << x.getNumber();

   x.printNumber();
   return 0;
}








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