Casting Away Constness
From: Trevor Lango (tmlango_at_sbcglobal.net)
Date: Fri, 02 Jan 2004 21:36:02 GMT
I want to be able to cast away the constness of a private member variable in
a member function of a class.
I have the private data member declared as follows:
const double x;
I have an overloaded assignment operator implemented as follows:
Point &Point::operator=( const Point *somePoint )
*( ( double * ) &x ) = somePoint->x;
Although the above compiles, I thought the newer more acceptable way to
accomplish this was using const_cast; however, I seem to not understand how
to implement const_cast. I tried the following:
const_cast< Point * >( this )->x = somePoint->x;
But this returns the following compiler error:
point.cpp: In method `class Point & Point::operator =(const Point *)':
point.cpp:58: assignment of read-only member `Point::x'
Can someone please enlighten me as to the proper use of const_cast to cast
away constness? Thanks in advance (and please excuse me if this has been
discussed already; I just subscribed to this newsgroup and searched as far
back as I could, but I couldn't find any mention of const_cast).