Do you use const member a lot?

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

    Do you use const member a lot?

    For many times, I've found myself changing my member variables from
    const back to non-const. No matter how good the original objective
    was, there was always at least one reason not to use const members.
    (swap, storing it in a container, etc.)
    Whereas in Java, 80% of the case, I would want "final" for my instance
    variables.

    It makes me think that is "const member variable" ever useful in C++?

    Maybe because of the value semantics of C++ objects, immutable
    programming is just not good for C++.

    static const is useful, const methods are useful, const parameters are
    useful, const T* is useful, but just cannot find niches for const
    member variables.

    So, what would you use const instance member variable for? Do you use
    it at all?
  • Phlip

    #2
    Re: Do you use const member a lot?

    Ben wrote:
    [color=blue]
    > For many times, I've found myself changing my member variables from
    > const back to non-const. No matter how good the original objective
    > was, there was always at least one reason not to use const members.
    > (swap, storing it in a container, etc.)
    > Whereas in Java, 80% of the case, I would want "final" for my instance
    > variables.
    >
    > It makes me think that is "const member variable" ever useful in C++?[/color]

    You have discovered that refactoring and re-featurizing are good.

    Program designs are never immutable. Aspects like 'const' or non-virtual can
    ensure that when you upgrade, you can lower the odds of breaking abilities.
    Start with the weakest constructions possible - constants, references,
    delegation - and only refactor towards mutables, pointers or inheritance as
    you find a need.

    --
    Phlip



    Comment

    • Mike Wahler

      #3
      Re: Do you use const member a lot?


      "Ben" <ben.yu@combine d.com> wrote in message
      news:245cee59.0 406111632.4bfea 4c4@posting.goo gle.com...[color=blue]
      > For many times, I've found myself changing my member variables from
      > const back to non-const. No matter how good the original objective
      > was, there was always at least one reason not to use const members.
      > (swap, storing it in a container, etc.)
      > Whereas in Java, 80% of the case, I would want "final" for my instance
      > variables.
      >
      > It makes me think that is "const member variable" ever useful in C++?
      >
      > Maybe because of the value semantics of C++ objects, immutable
      > programming is just not good for C++.
      >
      > static const is useful, const methods are useful, const parameters are
      > useful, const T* is useful, but just cannot find niches for const
      > member variables.
      >
      > So, what would you use const instance member variable for? Do you use
      > it at all?[/color]

      Some very old sage advice:

      When encountering a new tool, don't waste your time
      going around trying to find an application for it.

      Decide what you need to do, then locate the tools
      best suited for that task. While looking for the
      right tools, if you see some that don't fit your
      task, just leave them in the box.


      -Mike


      Comment

      • EventHelix.com

        #4
        Re: Do you use const member a lot?

        > So, what would you use const instance member variable for? Do you use[color=blue]
        > it at all?[/color]

        In the code I work with, I haven't seen a lot of const member variables.
        I do see const methods and parameters being used a lot.

        I guess there are few cases where a member variable can be initialized
        in the constructor and does not need to change for the lifetime of the
        object.

        Sandeep
        --
        Sequence diagram based systems engineering and architecture design tool. Built in support for alternative scenarios and multi-tier architectures.

        EventStudio 2.0 - System Architecture Design CASE Tool

        Comment

        • JKop

          #5
          Re: Do you use const member a lot?

          Ben posted:
          [color=blue]
          > For many times, I've found myself changing my member variables from
          > const back to non-const. No matter how good the original objective
          > was, there was always at least one reason not to use const members.
          > (swap, storing it in a container, etc.)
          > Whereas in Java, 80% of the case, I would want "final" for my instance
          > variables.
          >
          > It makes me think that is "const member variable" ever useful in C++?
          >
          > Maybe because of the value semantics of C++ objects, immutable
          > programming is just not good for C++.
          >
          > static const is useful, const methods are useful, const parameters are
          > useful, const T* is useful, but just cannot find niches for const
          > member variables.
          >
          > So, what would you use const instance member variable for? Do you use
          > it at all?[/color]


          class BankAccount
          {
          protected:

          const unsigned long account_number;

          public:

          BankAccount(uns igned long in_account_numb er) : account_number
          (in_account_num ber) { ; }

          };




          -JKop

          Comment

          • Thomas Matthews

            #6
            Re: Do you use const member a lot?

            Ben wrote:
            [snip]
            [color=blue]
            >
            > So, what would you use const instance member variable for? Do you use
            > it at all?[/color]
            I use const member variables for {named} constants
            used only within the class, member function or
            global function.


            --
            Thomas Matthews

            C++ newsgroup welcome message:

            C++ Faq: http://www.parashift.com/c++-faq-lite
            C Faq: http://www.eskimo.com/~scs/c-faq/top.html
            alt.comp.lang.l earn.c-c++ faq:

            Other sites:
            http://www.josuttis.com -- C++ STL Library book
            http://www.sgi.com/tech/stl -- Standard Template Library

            Comment

            • Ben

              #7
              Re: Do you use const member a lot?

              >[color=blue]
              > class BankAccount
              > {
              > protected:
              >
              > const unsigned long account_number;
              >
              > public:
              >
              > BankAccount(uns igned long in_account_numb er) : account_number
              > (in_account_num ber) { ; }
              >
              > };
              >
              >
              >
              >
              > -JKop[/color]

              This is similar to the stuff I normally start with. It looks innocent
              to have "const member" here. However, later, you will find it hard to
              store in a vector or an array. Users may complain it is hard to
              aggregate your BankAccount object into their own objects when they do
              want to change the bankaccount attribute.
              In short, this BankAccount is only good for use as a stack object,
              nothing else. And very rarely you will feel satisfied with that.

              Again, it is the value semantics that kills the attempt to be
              immutable.

              In java, even your object is immutable, users can always do functional
              update to get a new value if they want. And I do like that style. But
              this is not possible in C++.

              So, I'd like to conclude that "immutable programming" is dead in C++
              and "const member variable" is very rarely useful or just useless.

              Comment

              • JKop

                #8
                Re: Do you use const member a lot?

                Ben posted:
                [color=blue][color=green]
                >>
                >> class BankAccount
                >> {
                >> protected:
                >>
                >> const unsigned long account_number;
                >>
                >> public:
                >>
                >> BankAccount(uns igned long in_account_numb er) : account_number
                >> (in_account_num ber) { ; }
                >>
                >> };
                >>
                >>
                >>
                >>
                >> -JKop[/color]
                >
                > This is similar to the stuff I normally start with. It looks innocent
                > to have "const member" here. However, later, you will find it hard to
                > store in a vector or an array. Users may complain it is hard to
                > aggregate your BankAccount object into their own objects when they do
                > want to change the bankaccount attribute.
                > In short, this BankAccount is only good for use as a stack object,
                > nothing else. And very rarely you will feel satisfied with that.
                >
                > Again, it is the value semantics that kills the attempt to be
                > immutable.
                >
                > In java, even your object is immutable, users can always do functional
                > update to get a new value if they want. And I do like that style. But
                > this is not possible in C++.
                >
                > So, I'd like to conclude that "immutable programming" is dead in C++
                > and "const member variable" is very rarely useful or just useless.[/color]


                I was getting at something like the following:

                In a bank, the one sole piece of data by which a bank account is identified
                is the account_number. After that, things like Balance and Account Holder
                are just supplemental bits of data. You cannot change an account's number,
                to do so would be change the one piece of data by which the account can be
                identified. You would have to close the account and open a new one, which
                would have a new unique number.

                class BankAccount
                {
                protected:

                const unsigned long int account_number;
                char account_holder[30];

                public:

                BankAccount(cha r* in_account_hold er) : account_number
                (GenerateUnique AccountNumber() )
                {
                strcpy(in_accou nt_holder, account_holder) ;
                }

                };


                I know that my example is a bit crappy and you'd never have a class like so
                or anything, but I hope it shows what I'm getting at.


                -JKop

                Comment

                • Jerald Fijerald

                  #9
                  Re: Do you use const member a lot?

                  ben.yu@combined .com (Ben) wrote in message news:<245cee59. 0406111632.4bfe a4c4@posting.go ogle.com>...
                  [color=blue]
                  >
                  > It makes me think that is "const member variable" ever useful in C++?
                  >[/color]

                  It is very useful if you tend to see objects as alogrithms (and not as
                  factories, trains, railroads, baboons, etc).

                  For example, an algorithm:

                  class Algorithm
                  {
                  void f1 (); // calls f2
                  void f2 (); // calls f1
                  int common_data_of_ f1_and_f2;
                  public:
                  int result;
                  Algorithm (parameters); // calls f1 to get started
                  };

                  And that is used in a function

                  int foo ()
                  {
                  Algorithm A (UserTree, 123);
                  return A.result;
                  }

                  In such cases it makes sense to have const members for
                  puproses of optimization.

                  Best regards,

                  Gerald

                  Comment

                  • Ben

                    #10
                    Re: Do you use const member a lot?

                    > In a bank, the one sole piece of data by which a bank account is identified[color=blue]
                    > is the account_number. After that, things like Balance and Account Holder
                    > are just supplemental bits of data. You cannot change an account's number,
                    > to do so would be change the one piece of data by which the account can be
                    > identified. You would have to close the account and open a new one, which
                    > would have a new unique number.
                    >
                    > class BankAccount
                    > {
                    > protected:
                    >
                    > const unsigned long int account_number;
                    > char account_holder[30];
                    >
                    > public:
                    >
                    > BankAccount(cha r* in_account_hold er) : account_number
                    > (GenerateUnique AccountNumber() )
                    > {
                    > strcpy(in_accou nt_holder, account_holder) ;
                    > }
                    >
                    > };
                    >[/color]

                    I understand that there are many business logics that require certain
                    field to be const or certain objects to be read-only.

                    The question is: is it wise to do that with "const member"? You are
                    sure your object will never be stored in a vector?
                    You are sure users never want to aggregate your object?

                    Yes, "this field should not change", but that can be implemented in
                    many ways. In c++, it is hard to say that something can never change.
                    Whatever the business requirement is, you may just want to be able to
                    change it for implementation reasons such as performance or
                    convenience. Say, swap.

                    class MyObject{
                    BankAccount acc;
                    void swap(MyObject& other){
                    //how do I write this if I cannot change acc?
                    }
                    };

                    How exactly users want to use this class should be decided by the
                    user. It sounds to me a too brave decision for the class designer to
                    say "no, I don't want it to be in a container. And no, don't aggregate
                    me!"

                    It makes more sense to say it cannot change in certain modules or
                    places or time, which, can be achieved by means of private/protected
                    and adapters.

                    Is it worthwhile to sacrifice flexibility for "security"? Talking
                    about security, with pointer arithmetics and casting present, nothing
                    is real secure anyway.

                    Well. it now sounds more something about personal flavor. One may
                    insist that he does not care the so-called "flexibilit y" and changing
                    one field is simply unacceptable, period. I have no disregard against
                    such decision.

                    I myself just always found I had to go back and change that decision,
                    however innocent it looked originally.

                    Comment

                    • Ingo Nolden

                      #11
                      Re: Do you use const member a lot?

                      JKop <NULL@NULL.NULL > wrote in news:94Vyc.2113 $Z14.1904@news. indigo.ie:

                      [color=blue]
                      >
                      > I was getting at something like the following:
                      >
                      > In a bank, the one sole piece of data by which a bank account is
                      > identified is the account_number. After that, things like Balance and
                      > Account Holder are just supplemental bits of data. You cannot change
                      > an account's number, to do so would be change the one piece of data by
                      > which the account can be identified. You would have to close the
                      > account and open a new one, which would have a new unique number.
                      >
                      > class BankAccount
                      > {
                      > protected:
                      >
                      > const unsigned long int account_number;
                      > char account_holder[30];
                      >
                      > public:
                      >
                      > BankAccount(cha r* in_account_hold er) : account_number
                      > (GenerateUnique AccountNumber() )
                      > {
                      > strcpy(in_accou nt_holder, account_holder) ;
                      > }
                      >
                      > };
                      >
                      >
                      > I know that my example is a bit crappy and you'd never have a class
                      > like so or anything, but I hope it shows what I'm getting at.
                      >
                      >
                      > -JKop[/color]

                      I also think that a const member is sometimes useful. I have one application for it in my self
                      made Type inquiry. There is a Type class with some const members that hold the information of
                      the type, like the baseclass, the name string and a unique code. Then there ist a constructor,
                      that defines them similar to the bank account example above. Finally I have a const static
                      member for every type in the library that looks like that:
                      static const Type Polynom;

                      and

                      const Type Type::Polynom = Type( 0xff0f0f0f, "Polynom", &ObjectBase );

                      The constructor arguments are the values for the const members.

                      I don't know about compiler optimization issues, but for me it is the information that const
                      gives to the programmer. When I take an objects type code like pDerivedPoly->GetType( )->Code
                      then its good to see it is const so it is not for change and it cannot be changed
                      accidentially.

                      But, I didn't find this by looking for a purpose for const members, so it is probably true to
                      say don't look for purposes for your tools, look for the tools you have a purpose for.
                      On the other hand, if you don't try and get to know all possibilities ( tools in your box ),
                      how can you know you choose the best one in a langluage that offers many ways to do the same
                      thing.

                      cheers
                      Ingo

                      Comment

                      • JKop

                        #12
                        Re: Do you use const member a lot?

                        Ben posted:
                        [color=blue][color=green]
                        >> In a bank, the one sole piece of data by which a bank account is
                        >> identified is the account_number. After that, things like Balance and
                        >> Account Holder are just supplemental bits of data. You cannot change
                        >> an account's number, to do so would be change the one piece of data by
                        >> which the account can be identified. You would have to close the
                        >> account and open a new one, which would have a new unique number.
                        >>
                        >> class BankAccount
                        >> {
                        >> protected:
                        >>
                        >> const unsigned long int account_number;
                        >> char account_holder[30];
                        >>
                        >> public:
                        >>
                        >> BankAccount(cha r* in_account_hold er) : account_number
                        >> (GenerateUnique AccountNumber() )
                        >> {
                        >> strcpy(in_accou nt_holder, account_holder) ;
                        >> }
                        >>
                        >> };
                        >>[/color]
                        >
                        > I understand that there are many business logics that require certain
                        > field to be const or certain objects to be read-only.
                        >
                        > The question is: is it wise to do that with "const member"? You are
                        > sure your object will never be stored in a vector?
                        > You are sure users never want to aggregate your object?
                        >
                        > Yes, "this field should not change", but that can be implemented in
                        > many ways. In c++, it is hard to say that something can never change.
                        > Whatever the business requirement is, you may just want to be able to
                        > change it for implementation reasons such as performance or
                        > convenience. Say, swap.
                        >
                        > class MyObject{
                        > BankAccount acc;
                        > void swap(MyObject& other){
                        > //how do I write this if I cannot change acc?
                        > }
                        > };
                        >
                        > How exactly users want to use this class should be decided by the
                        > user. It sounds to me a too brave decision for the class designer to
                        > say "no, I don't want it to be in a container. And no, don't aggregate
                        > me!"
                        >
                        > It makes more sense to say it cannot change in certain modules or
                        > places or time, which, can be achieved by means of private/protected
                        > and adapters.
                        >
                        > Is it worthwhile to sacrifice flexibility for "security"? Talking
                        > about security, with pointer arithmetics and casting present, nothing
                        > is real secure anyway.
                        >
                        > Well. it now sounds more something about personal flavor. One may
                        > insist that he does not care the so-called "flexibilit y" and changing
                        > one field is simply unacceptable, period. I have no disregard against
                        > such decision.
                        >
                        > I myself just always found I had to go back and change that decision,
                        > however innocent it looked originally.[/color]

                        Could you please elaborate on how putting into into a container class could
                        complicate things? I've seen simple container classes before and all they do
                        is store a load of pointers to seperate objects. How will this intefer with
                        a const data member?!

                        -JKop

                        Comment

                        • Peter van Merkerk

                          #13
                          Re: Do you use const member a lot?

                          "Thomas Matthews" <Thomas_Matthew sSpamBotsSuck@s bcglobal.net> wrote in
                          message news:40CB0C04.2 080409@sbcgloba l.net...[color=blue][color=green]
                          > > So, what would you use const instance member variable for? Do you use
                          > > it at all?[/color]
                          > I use const member variables for {named} constants
                          > used only within the class, member function or
                          > global function.[/color]

                          Why not make those static const members?

                          FWIW I share the observations made by the OP ("static const is useful,
                          const methods are useful, const parameters are useful, const T* is useful,
                          but just cannot find niches for const member variables").

                          --
                          Peter van Merkerk
                          peter.van.merke rk(at)dse.nl




                          Comment

                          • tom_usenet

                            #14
                            Re: Do you use const member a lot?

                            On 11 Jun 2004 17:32:58 -0700, ben.yu@combined .com (Ben) wrote:
                            [color=blue]
                            >For many times, I've found myself changing my member variables from
                            >const back to non-const. No matter how good the original objective
                            >was, there was always at least one reason not to use const members.
                            >(swap, storing it in a container, etc.)[/color]

                            Only value type objects generally offer those operations. Most objects
                            aren't value type objects.
                            [color=blue]
                            >Whereas in Java, 80% of the case, I would want "final" for my instance
                            >variables.
                            >
                            >It makes me think that is "const member variable" ever useful in C++?
                            >
                            >Maybe because of the value semantics of C++ objects, immutable
                            >programming is just not good for C++.
                            >
                            >static const is useful, const methods are useful, const parameters are
                            >useful, const T* is useful, but just cannot find niches for const
                            >member variables.
                            >
                            >So, what would you use const instance member variable for? Do you use
                            >it at all?[/color]

                            Use it in business logic objects with immutable, per-instance values
                            that can be set in the initializer list.

                            Tom
                            --
                            C++ FAQ: http://www.parashift.com/c++-faq-lite/
                            C FAQ: http://www.eskimo.com/~scs/C-faq/top.html

                            Comment

                            • ralpe

                              #15
                              Re: Do you use const member a lot?

                              ben.yu@combined .com (Ben) wrote in message news:<245cee59. 0406122131.6e7f d9eb@posting.go ogle.com>...[color=blue][color=green]
                              > >
                              > > class BankAccount
                              > > {
                              > > protected:
                              > >
                              > > const unsigned long account_number;
                              > >
                              > > public:
                              > >
                              > > BankAccount(uns igned long in_account_numb er) : account_number
                              > > (in_account_num ber) { ; }
                              > >
                              > > };
                              > >
                              > >
                              > >
                              > >
                              > > -JKop[/color]
                              >
                              > This is similar to the stuff I normally start with. It looks innocent
                              > to have "const member" here. However, later, you will find it hard to
                              > store in a vector or an array. Users may complain it is hard to
                              > aggregate your BankAccount object into their own objects when they do
                              > want to change the bankaccount attribute.
                              > In short, this BankAccount is only good for use as a stack object,
                              > nothing else. And very rarely you will feel satisfied with that.
                              >
                              > Again, it is the value semantics that kills the attempt to be
                              > immutable.[/color]

                              Why would you want two BankAccount objects with the same account number (id)?

                              You should distinguish between values and entities.
                              Bank accounts should be non-copyable entities:

                              class BankAccount
                              {
                              public:

                              const int id;

                              BankAccount(int id) : id(id) {}

                              private:

                              BankAccount(Ban kAccount&); // not implemented
                              BankAccount operator=(BankA ccount&); // not implemented
                              };

                              Use (smart) pointers instead of values:

                              boost::shared_p tr<BankAccount>
                              [color=blue]
                              > In java, even your object is immutable, users can always do functional
                              > update to get a new value if they want. And I do like that style. But
                              > this is not possible in C++.
                              >
                              > So, I'd like to conclude that "immutable programming" is dead in C++
                              > and "const member variable" is very rarely useful or just useless.[/color]

                              Comment

                              Working...