CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 9 of 9

Thread: const keyword

  1. #1
    Join Date
    Jan 2006
    Posts
    28

    const keyword

    Hi all,

    I come across a question that

    whether 'const' keyword is applied to object abstract state or bitwise state.

    The answer was that const should be applied to object abstract state.

    But, const keyword ensures that object bitwise state is not changed.

    I am confused over here. Especially with this example.

    class MyString
    {
    char *m_sz;
    public:
    MyString( const char *s )
    {
    m_sz = strdup( s );
    }

    void toUpper() const
    {
    char *sz = m_sz;
    while( (*sz) != '\0' )
    {
    (*sz) -= 32;
    sz++;
    }
    }

    void Print() const
    {
    printf( "%s\n", m_sz );
    }
    };

    int main(int argc, char* argv[])
    {
    const MyString myStr( "hello world" );

    myStr.toUpper();
    myStr.Print();

    return 0;
    }

    Regards.

  2. #2
    Join Date
    Jan 2006
    Location
    Singapore
    Posts
    6,765

    Re: const keyword

    But, const keyword ensures that object bitwise state is not changed.
    No, it promises that the logical, observable state of the object is not changed by a call to the const member function. In particular, consider the mutable keyword and how it can be used to mark a member variable as modifiable even in a const member function.
    C + C++ Compiler: MinGW port of GCC
    Build + Version Control System: SCons + Bazaar

    Look up a C/C++ Reference and learn How To Ask Questions The Smart Way
    Kindly rate my posts if you found them useful

  3. #3
    Join Date
    Jan 2006
    Posts
    28

    Re: const keyword

    First of all clarify me, what is an observable state in this example.

    Also, keep to this specific example.

    Regards.

  4. #4
    Join Date
    Apr 1999
    Location
    Altrincham, England
    Posts
    4,470

    Re: const keyword

    Quote Originally Posted by salman83
    Code:
    void toUpper() const
        {
            char *sz = m_sz;
            while( (*sz) != '\0' )
            {
                (*sz) -= 32;
                sz++;
            }
        }
    The line in red shouldn't compile since m_sz has type const char* in that function. Also, marking a function called toUpper in that context as const is just perverse.

    As laserlight says, const marks (or should be considered as marking) a function as not changing the observable state of an object, since mutable members can be modified within a const function. This, of course, implies that any member marked mutable must not contribute to the observable state of an object.
    Correct is better than fast. Simple is better than complex. Clear is better than cute. Safe is better than insecure.
    --
    Sutter and Alexandrescu, C++ Coding Standards

    Programs must be written for people to read, and only incidentally for machines to execute.

    --
    Harold Abelson and Gerald Jay Sussman

    The cheapest, fastest and most reliable components of a computer system are those that aren't there.
    -- Gordon Bell


  5. #5
    Join Date
    Apr 1999
    Location
    Altrincham, England
    Posts
    4,470

    Re: const keyword

    The observable state is what a user of your class sees. That is, if I have an object of your class and I call a const function on that object, then I should not be able to detect any difference in the object's state before and after the call. In the example you've given, there is a difference, since the internal string (which I can "see" by printing it out) has changed, so the const is a lie.
    Correct is better than fast. Simple is better than complex. Clear is better than cute. Safe is better than insecure.
    --
    Sutter and Alexandrescu, C++ Coding Standards

    Programs must be written for people to read, and only incidentally for machines to execute.

    --
    Harold Abelson and Gerald Jay Sussman

    The cheapest, fastest and most reliable components of a computer system are those that aren't there.
    -- Gordon Bell


  6. #6
    Join Date
    Jan 2006
    Posts
    28

    Re: const keyword

    > In the example you've given, there is a difference, since the internal string (which I can "see" by printing it out) has changed, so the const is a lie.

    Yeah, it is a lie.

    Actually, const ensures that the object bit-wise state is not changed. In this case, 'm_sz' pointer is not changed but its data is changed.


    > char *sz = m_sz;

    I checked it out. It is compiling.

    Regards.

  7. #7
    Join Date
    Jan 2004
    Location
    Düsseldorf, Germany
    Posts
    2,401

    Re: const keyword

    Quote Originally Posted by Graham
    The line in red shouldn't compile since m_sz has type const char* in that function.
    Nope, m_sz has type char * const, not const char *. That's why it compiles.
    More computing sins are committed in the name of efficiency (without necessarily achieving it) than for any other single reason - including blind stupidity. --W.A.Wulf

    Premature optimization is the root of all evil --Donald E. Knuth


    Please read Information on posting before posting, especially the info on using [code] tags.

  8. #8
    Join Date
    Jan 2004
    Location
    Düsseldorf, Germany
    Posts
    2,401

    Re: const keyword

    To elaborate a bit more: m_sz is a pointer. The compiler cannot distinguish, if the data it points to is actually owned by the object or not. Consequently it cannot tell, if changing the data influences the observable state of the object (it might change the observable state of some other object). Therefore it is allowed to change data that is pointed to by a member variable in a const function.

    Now take an example without pointers and try adding const to this:
    Code:
    #include <string>
    #include <iostream>
    
    class MyString
    {
      std::string m_s;
    public:
      MyString( const char *s )
        : m_s(s)
      {}
    
      void toUpper()
      {
        for (std::string::iterator it = m_s.begin(); it != m_s.end(); ++it) {
          (*it) -= 32;
        }
      }
    
      void Print() const
      {
        std::cout << m_s;
      }
    };
    
    int main(int argc, char* argv[])
    {
      MyString myStr( "hello world" );
      myStr.toUpper();
      myStr.Print();
      
      return 0;
    }
    More computing sins are committed in the name of efficiency (without necessarily achieving it) than for any other single reason - including blind stupidity. --W.A.Wulf

    Premature optimization is the root of all evil --Donald E. Knuth


    Please read Information on posting before posting, especially the info on using [code] tags.

  9. #9
    Join Date
    Apr 1999
    Location
    Altrincham, England
    Posts
    4,470

    Re: const keyword

    Quote Originally Posted by treuss
    Nope, m_sz has type char * const, not const char *. That's why it compiles.
    <smacks head>Of course. Non-transitive constness... it was late, I was tired. That's my excuse.

    I think that there's a serious point to be made here about the difference between what is syntactically correct and what is semantically desirable. With a const function, we want observable constness, yet the non-transitive rule and the mutable keyword mean that the only real way that it can be properly guaranteed is for the coder to be careful and to enforce it deliberately. The compiler will help a bit, but there are syntactically correct constructs where the rules won't enforce what we expect the semantics to be.
    Correct is better than fast. Simple is better than complex. Clear is better than cute. Safe is better than insecure.
    --
    Sutter and Alexandrescu, C++ Coding Standards

    Programs must be written for people to read, and only incidentally for machines to execute.

    --
    Harold Abelson and Gerald Jay Sussman

    The cheapest, fastest and most reliable components of a computer system are those that aren't there.
    -- Gordon Bell


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured