const?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • DumRat
    New Member
    • Mar 2007
    • 93

    #1

    const?

    Can anyone tell me what the const keyword placed like this does?

    int GetVariable() const;

    What does const here mean? Thanks.
  • gpraghuram
    Recognized Expert Top Contributor
    • Mar 2007
    • 1275

    #2
    Hi,
    The const tells that you can modify the memeber variable inside the function.
    Take this example
    Code:
    class A{
    int x;
    int GetVariable() const
    {
        x++; //[B]Will give error during compilation[/B]}
    };
    Thanks
    Raghuram

    Comment

    • Banfa
      Recognized Expert Expert
      • Feb 2006
      • 9067

      #3
      and because no member variables can be changed it effectively makes the this pointer constant too.

      Comment

      • jesusdiehard
        New Member
        • Apr 2007
        • 18

        #4
        its feature of C++ for turning function into accessor function i.e. they can't change the state of object i.e. member variables are non editable in this function

        you can get away with that using mutable keyword preceding the member variable declaration.

        class xyz
        {

        mutable int x;
        int y;

        void function func( ) const / /accessor function
        {
        //y++; it will generate a error
        x++; //it will not generate a error, law for breaking law
        }

        };



        Originally posted by DumRat
        Can anyone tell me what the const keyword placed like this does?

        int GetVariable() const;

        What does const here mean? Thanks.

        Comment

        • weaknessforcats
          Recognized Expert Expert
          • Mar 2007
          • 9214

          #5
          Just keep in mind that a const member function is prohibited from changing class data members.

          Unless you have const member functions you cannot have const objects becuse the compiler will worry the member functions will change the object and violate the const-ness.

          Also, any functions called from inside a const member function must also be const ot have const arguments.

          The mutable keyword itdentifies those data members in an object that do not participate in the const-ness of the object.

          Comment

          Working...