Use const_cast on a const reference. : cast « Class « C++






Use const_cast on a const reference.

Use const_cast on a const reference.
   
#include <iostream>
using namespace std;
   
void sqrval(const int &val)
{
  // cast away const on val
  const_cast<int &> (val) = val * val;
}
   
int main()
{
  int x = 10;
   
  cout << "x before call: " << x << endl;
  sqrval(x);
  cout << "x after call: " << x << endl;
   
  return 0;
}
  
    
    
  








Related examples in the same category

1.Don't need a cast to go up the inheritance hierarchy
2.class type-casting
3.The const_cast operator is used to explicitly override const and/or volatile in a cast.
4.The static_cast operator performs a nonpolymorphic cast.
5.The reinterpret_cast operator converts one type into a fundamentally different type.
6.The dynamic_cast performs a run-time cast that verifies the validity of a cast.
7.Replacing typeid with dynamic_cast