Casting Away Constness

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Trevor Lango

    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.

    I have the private data member declared as follows:

    const double x;

    I have an overloaded assignment operator implemented as follows:

    Point &Point::operato r=( 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).


  • Jeff Schwab

    #2
    Re: Casting Away Constness

    Trevor Lango wrote:[color=blue]
    > I want to be able to cast away the constness of a private member variable in
    > a member function of a class.[/color]

    Are you familiar with the "mutable" keword?
    [color=blue]
    > I have the private data member declared as follows:
    >
    > const double x;[/color]

    Why did you declare it const, if you knew you were going to change it?
    [color=blue]
    > I have an overloaded assignment operator implemented as follows:
    >
    > Point &Point::operato r=( 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'[/color]

    You "unconsted" the Point object. The member "x" was const for a
    different reason, namely because you declared it thus.
    [color=blue]
    > Can someone please enlighten me as to the proper use of const_cast to cast
    > away constness?[/color]

    const_cast< double >( x ) = somePoint->x;

    If you find yourself needing const cast, there is an inconsistency
    somewhere in your program. If you understand what the inconsistency is,
    and you're OK with it, you still might consider a mutable member as an
    alternative to the cast.
    [color=blue]
    > 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).[/color]

    Welcome!

    -Jeff

    Comment

    • Victor Bazarov

      #3
      Re: Casting Away Constness

      "Trevor Lango" <tmlango@sbcglo bal.net> wrote...[color=blue]
      > I want to be able to cast away the constness of a private member variable[/color]
      in[color=blue]
      > a member function of a class.
      >
      > I have the private data member declared as follows:
      >
      > const double x;[/color]

      Why const?
      [color=blue]
      >
      > I have an overloaded assignment operator implemented as follows:
      >
      > Point &Point::operato r=( const Point *somePoint )[/color]

      Why are you assigning from a pointer? One rather strange assignment op.
      Well, no matter...
      [color=blue]
      > {
      > *( ( double * ) &x ) = somePoint->x;[/color]

      Simpler would be

      (double&) x = somePoint->x;
      [color=blue]
      > }
      >
      > Although the above compiles, I thought the newer more acceptable way to
      > accomplish this was using const_cast; however, I seem to not understand[/color]
      how[color=blue]
      > 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'[/color]

      You cast away constness of the object itself, which is (a) unneeded because
      the object is already non-const and (b) doesn't affect the const-ness of
      a member declared explicitly const.

      You _could_ do

      const_cast<doub le&>(x) = somePoint->x;

      But still, you have to answer this question: why did you make the member
      'const' in the first place?
      [color=blue]
      >
      > Can someone please enlighten me as to the proper use of const_cast to cast
      > away constness?[/color]

      I think you need some enlightment as to proper use of const before you
      attempt using const_cast... But that's just the impression I get.
      [color=blue]
      > 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).[/color]

      Casting away const-ness is not what you should be doing casually. In
      most cases if you cast away const-ness, you _must_ be sure that the
      original object _was_ declared/defined as non-const, otherwise UB occurs.

      Victor


      Comment

      • Ron Natalie

        #4
        Re: Casting Away Constness


        "Trevor Lango" <tmlango@sbcglo bal.net> wrote in message news:6vlJb.4740 $Xe7.1689@newss vr27.news.prodi gy.com...[color=blue]
        > I want to be able to cast away the constness of a private member variable in
        > const_cast< Point * >( this )->x = somePoint->x;[/color]
        *const_cast<Poi nt*>(&x) = somePoint->x;
        or
        const_cast<Poin t&>(x) = somePoint->x;

        Comment

        • Ron Natalie

          #5
          Re: Casting Away Constness


          "Trevor Lango" <tmlango@sbcglo bal.net> wrote in message news:6vlJb.4740 $Xe7.1689@newss vr27.news.prodi gy.com...[color=blue]
          > 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::operato r=( const Point *somePoint )
          > {
          > *( ( double * ) &x ) = somePoint->x;
          > }
          >[/color]
          Oops, I got confused before:
          *const_cast<dou ble*>(&x) = somePoint->x;
          or
          const_cast<doub le&>(x) = somePoint->x

          Comment

          • Ron Natalie

            #6
            Re: Casting Away Constness


            "Jeff Schwab" <jeffplus@comca st.net> wrote in message news:0YOdnUZgDs Dnemii4p2dnA@co mcast.com...[color=blue]
            > Trevor Lango wrote:[color=green]
            > > I want to be able to cast away the constness of a private member variable in
            > > a member function of a class.[/color]
            >
            > Are you familiar with the "mutable" keword?[/color]

            He might be, but it wouldn't help. He has a const member in a non-const object
            he wishes to change. Mutable would allow him to change a member in a CONST
            object.

            Comment

            • Jeff Schwab

              #7
              Re: Casting Away Constness

              Jeff Schwab wrote:[color=blue]
              > Trevor Lango wrote:
              >[color=green]
              >> I want to be able to cast away the constness of a private member
              >> variable in a member function of a class.[/color]
              >
              >
              > Are you familiar with the "mutable" keyword?
              >[color=green]
              >> I have the private data member declared as follows:
              >>
              >> const double x;[/color]
              >
              > Why did you declare it const, if you knew you were going to change it?
              >[color=green]
              >> I have an overloaded assignment operator implemented as follows:
              >>
              >> Point &Point::operato r=( 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'[/color]
              >
              >
              > You "unconsted" the Point object. The member "x" was const for a
              > different reason, namely because you declared it thus.
              >[color=green]
              >> Can someone please enlighten me as to the proper use of const_cast to
              >> cast
              >> away constness?[/color]
              >
              >
              > const_cast< double >( x ) = somePoint->x;[/color]

              Sorry, that should say:

              const_cast< double >( x ) = somePoint->x;

              Btw, const_cast is not guaranteed to work. You may get a silent error
              at run time. Try making the member mutable, or at least not declaring
              it const.
              [color=blue]
              > If you find yourself needing const cast, there is an inconsistency
              > somewhere in your program. If you understand what the inconsistency is,
              > and you're OK with it, you still might consider a mutable member as an
              > alternative to the cast.
              >[color=green]
              >> 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).[/color]
              >
              >
              > Welcome!
              >
              > -Jeff
              >[/color]

              Comment

              • Jeff Schwab

                #8
                Re: Casting Away Constness

                Ron Natalie wrote:[color=blue]
                > "Jeff Schwab" <jeffplus@comca st.net> wrote in message news:0YOdnUZgDs Dnemii4p2dnA@co mcast.com...
                >[color=green]
                >>Trevor Lango wrote:
                >>[color=darkred]
                >>>I want to be able to cast away the constness of a private member variable in
                >>>a member function of a class.[/color]
                >>
                >>Are you familiar with the "mutable" keword?[/color]
                >
                >
                > He might be, but it wouldn't help. He has a const member in a non-const object
                > he wishes to change. Mutable would allow him to change a member in a CONST
                > object.[/color]

                Yes, not declaring the member "const" in the first place certainly would
                help. :)

                Comment

                • Trevor Lango

                  #9
                  Re: Casting Away Constness


                  "Jeff Schwab" <jeffplus@comca st.net> wrote in message
                  news:0YOdnUZgDs Dnemii4p2dnA@co mcast.com...[color=blue]
                  > Trevor Lango wrote:[color=green]
                  > > I want to be able to cast away the constness of a private member[/color][/color]
                  variable in[color=blue][color=green]
                  > > a member function of a class.[/color]
                  >
                  > Are you familiar with the "mutable" keword?[/color]

                  I thought the mutable keyword was for allowing modification of private
                  member variables in class objects declared as const...?
                  [color=blue][color=green]
                  > > I have the private data member declared as follows:
                  > >
                  > > const double x;[/color]
                  >
                  > Why did you declare it const, if you knew you were going to change it?[/color]

                  I didn't want anything to be able to modify it except for the overloaded
                  assignment operator.

                  [snipped for readability]


                  Comment

                  • Trevor Lango

                    #10
                    Re: Casting Away Constness


                    "Jeff Schwab" <jeffplus@comca st.net> wrote in message
                    news:8rGdneEHQq VqdGiiRVn-tA@comcast.com. ..[color=blue]
                    > Ron Natalie wrote:[color=green]
                    > > "Jeff Schwab" <jeffplus@comca st.net> wrote in message[/color][/color]
                    news:0YOdnUZgDs Dnemii4p2dnA@co mcast.com...[color=blue][color=green]
                    > >[color=darkred]
                    > >>Trevor Lango wrote:
                    > >>
                    > >>>I want to be able to cast away the constness of a private member[/color][/color][/color]
                    variable in[color=blue][color=green][color=darkred]
                    > >>>a member function of a class.
                    > >>
                    > >>Are you familiar with the "mutable" keword?[/color]
                    > >
                    > >
                    > > He might be, but it wouldn't help. He has a const member in a[/color][/color]
                    non-const object[color=blue][color=green]
                    > > he wishes to change. Mutable would allow him to change a member in a[/color][/color]
                    CONST[color=blue][color=green]
                    > > object.[/color]
                    >
                    > Yes, not declaring the member "const" in the first place certainly would
                    > help. :)
                    >[/color]

                    After some further thought I do not believe I will implement those private
                    member variables as const. However, I do appreciate the clarification of the
                    proper syntax for implementing const_cast. For those of you who posted the
                    appropriate syntax, can you please cite what documentation you referenced to
                    provide your answers? Thanks!


                    Comment

                    • Ron Natalie

                      #11
                      Re: Casting Away Constness


                      "Jeff Schwab" <jeffplus@comca st.net> wrote in message news:MY6dndBDsI 4TdGiiRVn-jA@comcast.com. ..[color=blue][color=green][color=darkred]
                      >> > const_cast< double >( x ) = somePoint->x;[/color][/color]
                      >
                      > Sorry, that should say:
                      >
                      > const_cast< double >( x ) = somePoint->x;[/color]
                      That loks the same to me, you mean
                      const_cast<doub le&>(x) = somePoint->x;
                      [color=blue]
                      >
                      > Btw, const_cast is not guaranteed to work. You may get a silent error
                      > at run time. Try making the member mutable, or at least not declaring
                      > it const.[/color]

                      There's no point in making it mutable. The member function he is running
                      is not CONST, hence the member is wouldn't be const if he didn't explicitly
                      make it so.

                      Comment

                      • Jeff Schwab

                        #12
                        Re: Casting Away Constness

                        Trevor Lango wrote:[color=blue]
                        > "Jeff Schwab" <jeffplus@comca st.net> wrote in message
                        > news:0YOdnUZgDs Dnemii4p2dnA@co mcast.com...
                        >[color=green]
                        >>Trevor Lango wrote:
                        >>[color=darkred]
                        >>>I want to be able to cast away the constness of a private member[/color][/color]
                        >
                        > variable in
                        >[color=green][color=darkred]
                        >>>a member function of a class.[/color]
                        >>
                        >>Are you familiar with the "mutable" keword?[/color]
                        >
                        >
                        > I thought the mutable keyword was for allowing modification of private
                        > member variables in class objects declared as const...?[/color]

                        Exactly. You were casting away the constness of the object just long
                        enough to modify a member variable. That's exactly the sort of cast
                        "mutable" was meant to help you avoid.
                        [color=blue][color=green][color=darkred]
                        >>>I have the private data member declared as follows:
                        >>>
                        >>> const double x;[/color]
                        >>
                        >>Why did you declare it const, if you knew you were going to change it?[/color]
                        >
                        >
                        > I didn't want anything to be able to modify it except for the overloaded
                        > assignment operator.[/color]

                        Hmmm... I'm not sure of a way to make that sort of guarantee, although
                        I do see what you mean.
                        [color=blue]
                        >
                        > [snipped for readability]
                        >
                        >[/color]

                        Comment

                        • Jeff Schwab

                          #13
                          Re: Casting Away Constness

                          Ron Natalie wrote:[color=blue]
                          > "Jeff Schwab" <jeffplus@comca st.net> wrote in message news:MY6dndBDsI 4TdGiiRVn-jA@comcast.com. ..
                          >[color=green][color=darkred]
                          >>>>const_cas t< double >( x ) = somePoint->x;[/color]
                          >>
                          >>Sorry, that should say:
                          >>
                          >> const_cast< double >( x ) = somePoint->x;[/color]
                          >
                          > That loks the same to me, you mean
                          > const_cast<doub le&>(x) = somePoint->x;[/color]

                          Right, thank you.
                          [color=blue]
                          >
                          >[color=green]
                          >>Btw, const_cast is not guaranteed to work. You may get a silent error
                          >>at run time. Try making the member mutable, or at least not declaring
                          >>it const.[/color]
                          >
                          >
                          > There's no point in making it mutable. The member function he is running
                          > is not CONST, hence the member is wouldn't be const if he didn't explicitly
                          > make it so.[/color]

                          Since the OP has explained further, I agree. He wasn't actually casting
                          away the constness of the variable though, he was casting away the
                          constness of the object. I was offering mutable as a suggestion to
                          achieve a similar effect, much as you suggested this:

                          const_cast<Poin t&>(x) = somePoint->x;


                          Comment

                          • Ron Natalie

                            #14
                            Re: Casting Away Constness


                            "Jeff Schwab" <jeffplus@comca st.net> wrote in message news:_LCdnWgV8N 9GcWiiRVn-ig@comcast.com. ..[color=blue][color=green]
                            > >
                            > > I thought the mutable keyword was for allowing modification of private
                            > > member variables in class objects declared as const...?[/color]
                            >
                            > Exactly. You were casting away the constness of the object just long
                            > enough to modify a member variable. That's exactly the sort of cast
                            > "mutable" was meant to help you avoid.[/color]

                            The object wasn't const. The member was.

                            Comment

                            • Ron Natalie

                              #15
                              Re: Casting Away Constness


                              "Trevor Lango" <tmlango@sbcglo bal.net> wrote in message news:LYlJb.4745 $2w7.984@newssv r27.news.prodig y.com...[color=blue]
                              > After some further thought I do not believe I will implement those private
                              > member variables as const. However, I do appreciate the clarification of the
                              > proper syntax for implementing const_cast. For those of you who posted the
                              > appropriate syntax, can you please cite what documentation you referenced to
                              > provide your answers? Thanks!
                              >[/color]
                              I didn't have to reference anything. If you spend several years actually writing
                              code you know these things :-)

                              5.2.11 of the standard pretty nicely explains this (and points you to the section
                              that warns you that what you're doing is undefined).

                              Comment

                              Working...