Casting Away Constness

From: Trevor Lango (tmlango_at_sbcglobal.net)
Date: 01/02/04


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).



Relevant Pages

  • Re: Casting Away Constness
    ... > a member function of a class. ... Why const? ... You cast away constness of the object itself, ...
    (comp.lang.cpp)
  • Re: Casting Away Constness
    ... > a member function of a class. ... Why did you declare it const, if you knew you were going to change it? ... > away constness? ... If you find yourself needing const cast, ...
    (comp.lang.cpp)
  • Re: Casting Away Constness
    ... >> I want to be able to cast away the constness of a private member ... >> variable in a member function of a class. ... > Why did you declare it const, if you knew you were going to change it? ...
    (comp.lang.cpp)
  • Re: Casting Away Constness
    ... > I want to be able to cast away the constness of a private member variable in ... > a member function of a class. ...
    (comp.lang.cpp)
  • Re: The importance of Kid Vulcan as a new X-Man?
    ... successful addition to the X-Men cast, primarily as a new X-Man. ... character will be the one to break this rut. ... Will it be Kid Vulcan? ... he's going to be a member of the X-Men. ...
    (rec.arts.comics.marvel.xbooks)