Short question

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Charles Keepax

    Short question

    Just a little quick question what is the effect of putting a const after
    a member function definition.

    Charles

  • Victor Bazarov

    #2
    Re: Short question

    "Charles Keepax" <s9903977@sms.e d.ac.uk> wrote...[color=blue]
    > Just a little quick question what is the effect of putting a const after
    > a member function definition.[/color]

    It makes the function 'const'. Inside it 'this' designates
    a constant object. Functions can be overloaded based on that.
    For a non-const object non-const function is preferred, for
    a const object only a const function will be called.

    struct A {
    A() {}
    void foo() const;
    void foo();
    };

    int main() {
    A a;
    a.foo(); // non-const is called
    const A ca;
    ca.foo(); // const is called
    }

    Doesn't the book on C++ that you're using for study explain
    all that?

    Victor


    Comment

    • John Harrison

      #3
      Re: Short question


      "Charles Keepax" <s9903977@sms.e d.ac.uk> wrote in message
      news:bf0vem$eqm $1@scotsman.ed. ac.uk...[color=blue]
      > Just a little quick question what is the effect of putting a const after
      > a member function definition.
      >
      > Charles
      >[/color]

      Its a guarantee that the member function will not alter the object it is
      called on. It means that the member function can be called on a const object
      or via a const reference or const pointer.

      John


      Comment

      • Josephine Schafer

        #4
        Re: Short question


        "Charles Keepax" <s9903977@sms.e d.ac.uk> wrote in message
        news:bf0vem$eqm $1@scotsman.ed. ac.uk...[color=blue]
        > Just a little quick question what is the effect of putting a const after
        > a member function definition.
        >[/color]
        Little quick answer :-)
        The function does not modify the state of the object/class..
        There are two camps on what that implies -
        bitwise constness or abstract state constness.
        Bitwise constness implies that no member variable gets modified.
        For abstract constness consider a class
        class A{
        public :
        void copy () ; // changes what p points to, not p..hence not const

        private:
        char *p;
        };

        Even if there is bitwise constness ( p unchanged) but if the contents of
        what p points to get changed then
        it is not abstract state constness.

        --
        With best wishes
        J.Schafer


        Comment

        Working...