Two questions about...something

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

    Two questions about...something


    I'm reading a STL book right now, and there I've
    picked up the folowing syntax:

    class C {
    private:
    int value;
    public:
    C(int initValue) : value(initValue ) { }
    }

    I can see what it does, but...why? Why is it written
    this way, and not like:

    class C {
    private:
    int value;
    public:
    C(int initValue) {
    value = initValue;
    }
    }

    The first snippet looks like some inherit-stuff, but
    obviously it's initializing the private member. So why
    is this syntax used, and is it at all different from
    the second snippet quality-wise?

    --
    Fred H

    void FredH::Contact( ) {
    TextToSpeach.sa y("frode at age dee dee dot en oh");
    }
  • Victor Bazarov

    #2
    Re: Two questions about...somethi ng

    "Fred H" <secret@nospam. com> wrote...[color=blue]
    >
    > I'm reading a STL book right now, and there I've
    > picked up the folowing syntax:
    >
    > class C {
    > private:
    > int value;
    > public:
    > C(int initValue) : value(initValue ) { }
    > }
    >
    > I can see what it does, but...why? Why is it written
    > this way, and not like:
    >
    > class C {
    > private:
    > int value;
    > public:
    > C(int initValue) {
    > value = initValue;
    > }
    > }
    >
    > The first snippet looks like some inherit-stuff, but
    > obviously it's initializing the private member. So why
    > is this syntax used, and is it at all different from
    > the second snippet quality-wise?[/color]

    This is covered in the FAQ. Please read FAQ before posting.

    I think you started reading the STL book too early. You need
    a C++ book and enough time with it so you don't ask questions
    like that.

    Victor


    Comment

    • Christoph Rabel

      #3
      Re: Two questions about...somethi ng

      Fred H wrote:[color=blue]
      >
      > The first snippet looks like some inherit-stuff, but
      > obviously it's initializing the private member. So why
      > is this syntax used, and is it at all different from
      > the second snippet quality-wise?[/color]

      1)
      The first snipped is initialization, the second one
      assignment. Here with the int it doesnt make much
      difference. But consider:

      class C {
      private:
      SomeExpensiveCl ass value;
      public:
      C(SomeExpensive Class initValue) : value(initValue ) { }
      }

      In the first snipped the initValue is used to construct the
      value.
      In the second snipped value is default constructed. Then
      initValue is assigned to value. This is most often very
      inefficient.

      2)
      class C {
      private:
      const int value;
      public:
      C(int initValue) : value(initValue ) { }
      }

      Const members can only be initialized, not set. So the
      second snippet doesnt work with the above code.

      3)
      Using initialization instead of assignment is considered
      good style. So prefer to write your constructors like the
      first snipped.

      hth

      Christoph

      Comment

      • John Harrison

        #4
        Re: Two questions about...somethi ng


        "Fred H" <secret@nospam. com> wrote in message
        news:opr2qzu5b0 qlpr0e@news.mim er.no...[color=blue]
        >
        > I'm reading a STL book right now, and there I've
        > picked up the folowing syntax:
        >
        > class C {
        > private:
        > int value;
        > public:
        > C(int initValue) : value(initValue ) { }
        > }
        >
        > I can see what it does, but...why? Why is it written
        > this way, and not like:
        >
        > class C {
        > private:
        > int value;
        > public:
        > C(int initValue) {
        > value = initValue;
        > }
        > }
        >
        > The first snippet looks like some inherit-stuff, but
        > obviously it's initializing the private member. So why
        > is this syntax used, and is it at all different from
        > the second snippet quality-wise?[/color]

        The first is initialization, the second is assignment. Assignment and
        initialization are not the same thing.

        In the second example value is first default initalized and then assigned.
        For an integer this make no difference because default initialization is a
        no-op. But for a class it might not be.

        class X()
        {
        X(); // default initialization, expensive
        X(const X&) // copy initialization, expensive
        X& operator=(const X&); // assignment, expensive
        };

        Now this code only does copy initialization

        class C
        {
        C(const X& xx) : x(xx) {}
        X x;
        };

        But this code does default initialization followed by assignment

        class C
        {
        C(const X& xx) { x = xx; }
        X x;
        };

        That's two expensive operations compared to one.

        So it's generally thought to be good style to prefer initialzation to
        assignment in constructors, even when it makes no actual difference, as is
        the case with int's.

        john


        Comment

        • Phlip

          #5
          Re: Two questions about...somethi ng

          Fred H wrote:
          [color=blue]
          > class C {
          > private:
          > int value;
          > public:
          > C(int initValue) : value(initValue ) { }
          > }[/color]
          [color=blue]
          > class C {
          > private:
          > int value;
          > public:
          > C(int initValue) {
          > value = initValue;
          > }
          > }
          >
          > The first snippet looks like some inherit-stuff, but
          > obviously it's initializing the private member. So why
          > is this syntax used, and is it at all different from
          > the second snippet quality-wise?[/color]

          Read /Effective C++/ by Jon Bon Jovi.

          Stare at this expression:

          C(int initValue) /*yo*/ {
          value = initValue;
          }

          In the place where I added /*yo*/ there's a trivial constructor for 'value'.
          Because 'value' is an 'int', that constructor is so trivial it does nothing.
          But it's still conceptually there.

          If 'value' were a 'SimCity', not an 'int', then its constructor might not be
          trivial. In that case, we should not waste time assigning to the 'SimCity'
          again inside the C constructor body.

          If there were more than one member, then their constructors, even if they do
          nothing, would still be there, and would still be in the same order as they
          declare in the class body. And C's destructor (which is also really there)
          would destroy them in reverse order. So declaring non-trivial constructions
          for each members, in the same order as they declare, improves your cognitive
          awareness.

          Ultimately, the only reason the STL book did it was to set a good example.
          There are some engineer decisions with different costs and benefits, and we
          must carefully experiment to make that decision cheaply. In this case, there
          are myriad subtle benefits to constructing members with sub-constructor
          notation, and no benefits to neglecting their construction. So follow the
          STL book's example.


          --
          Phlip



          Comment

          • Fred H

            #6
            Re: Two questions about...somethi ng


            Guess who forgot to change the subject line... :\

            --
            Fred H

            void FredH::Contact( ) {
            TextToSpeach.sa y("frode at age dee dee dot en oh");
            }

            Comment

            • David Harmon

              #7
              Re: Two questions about...somethi ng

              On Mon, 02 Feb 2004 14:58:08 GMT in comp.lang.c++, Fred H
              <secret@nospam. com> was alleged to have written:[color=blue]
              > C(int initValue) : value(initValue ) { }
              >}
              >
              >I can see what it does, but...why? Why is it written
              >this way,[/color]

              It's called the initialization list, and it means the member variable
              itself is constructed according to the specification there, instead of
              being initialized according to the default and then assigned some value
              in the body of your constructor. Might be mote efficient but probably
              makes no difference for an 'int'. Makes a bigger difference if the
              member variable is of a class with its own constructor.

              This issue is covered in Marshall Cline's C++ FAQ. See the topic
              "[10.6] Should my constructors use "initializa tion lists" or
              "assignment "?" It is always good to check the FAQ before posting.
              You can get the FAQ at:



              Comment

              • Martijn Lievaart

                #8
                Re: Two questions about...somethi ng

                On Mon, 02 Feb 2004 14:58:08 +0000, Fred H wrote:
                [color=blue]
                >
                > I'm reading a STL book right now, and there I've
                > picked up the folowing syntax:
                >
                > class C {
                > private:
                > int value;
                > public:
                > C(int initValue) : value(initValue ) { }
                > }
                >
                > I can see what it does, but...why? Why is it written
                > this way, and not like:
                >
                > class C {
                > private:
                > int value;
                > public:
                > C(int initValue) {
                > value = initValue;
                > }
                > }
                >
                > The first snippet looks like some inherit-stuff, but
                > obviously it's initializing the private member. So why
                > is this syntax used, and is it at all different from
                > the second snippet quality-wise?[/color]

                Yes, the second snippet assigns, instead of initialising. For an int, the
                net result is exactly the same (given any decent compiler) but if value is
                some complex object there can be a huge difference.

                Apart from that, some things can only be initialised, not assigned to.
                Const objects are one, references another, and maybe I missed one.

                HTH,
                M4

                Comment

                • jeffc

                  #9
                  Re: Two questions about...somethi ng


                  "Fred H" <secret@nospam. com> wrote in message
                  news:opr2qzu5b0 qlpr0e@news.mim er.no...[color=blue]
                  >
                  > I'm reading a STL book right now, and there I've
                  > picked up the folowing syntax:
                  >
                  > class C {
                  > private:
                  > int value;
                  > public:
                  > C(int initValue) : value(initValue ) { }
                  > }
                  >
                  > I can see what it does, but...why? Why is it written
                  > this way, and not like:
                  >
                  > class C {
                  > private:
                  > int value;
                  > public:
                  > C(int initValue) {
                  > value = initValue;
                  > }
                  > }
                  >
                  > The first snippet looks like some inherit-stuff, but
                  > obviously it's initializing the private member. So why
                  > is this syntax used, and is it at all different from
                  > the second snippet quality-wise?[/color]

                  No, in this case it's basically the same. There are 2 reasons (IMO) this is
                  used.
                  1) to be consistent with initializing *all* parts of the class. Your
                  private member is an int. What if it were an instance of another class?
                  Then you'd have to call the constructor for that class to initialize it
                  (assuming it had a constructor with some parameters.) Think of your in
                  variable as an object.
                  2) in general it's always better to initialize variables ASAP. This is true
                  in traditional programming too. Always initialiaze your variables as soon
                  as you can. With C++ and OO, you have a new method for initializing
                  variables even sooner - before your constructor code actually starts.
                  Exploit this.


                  Comment

                  • Fred H

                    #10
                    Re: Two questions about...somethi ng


                    [Completely OT]
                    [color=blue]
                    > This is covered in the FAQ. Please read FAQ before posting.
                    >
                    > I think you started reading the STL book too early. You need
                    > a C++ book and enough time with it so you don't ask questions
                    > like that.
                    >
                    > Victor[/color]

                    I have read the FAQ, and I search it quite often. But this time
                    I didn't know what to search for. Now I know that I could have
                    searched for "initializaion" , and found FAQ 10.6, but hey, I can't
                    read the whole FAQ through every time I have a question, can I...?

                    Regarding starting the STL book too early, you might be right. I was
                    hoping it would suffice to read half a dozen or so online tutorials,
                    and then start using my STL book, but I'm comming to the conclusion
                    that I might actually need to buy a good tutorial/reference book. So
                    I've started reaserching for good books.

                    But I still can't see why people like you allways need to tell people
                    like me, that we really ought not to post in this group.

                    What kind of activities is it you'd like there to be in this group,
                    if newbies just isn't allowed here? I allways thought that
                    comp.lang.c++.m oderated was the newbie free zone around here...

                    [/Completely OT]

                    To all you other good people who answered my question: Thanks a lot :-)


                    --
                    Fred H

                    void FredH::Contact( ) {
                    TextToSpeach.sa y("frode at age dee dee dot en oh");
                    }

                    Comment

                    • Karl Heinz Buchegger

                      #11
                      Re: Two questions about...somethi ng

                      Fred H wrote:[color=blue]
                      >
                      > I'm reading a STL book right now, and there I've
                      > picked up the folowing syntax:
                      >
                      > class C {
                      > private:
                      > int value;
                      > public:
                      > C(int initValue) : value(initValue ) { }
                      > }
                      >
                      > I can see what it does, but...why? Why is it written
                      > this way, and not like:
                      >
                      > class C {
                      > private:
                      > int value;
                      > public:
                      > C(int initValue) {
                      > value = initValue;
                      > }
                      > }
                      >
                      > The first snippet looks like some inherit-stuff, but
                      > obviously it's initializing the private member. So why
                      > is this syntax used, and is it at all different from
                      > the second snippet quality-wise?[/color]

                      The first one is a true initialization, while the second
                      one is an assignment. Granted it doesn't make much of
                      a difference in this specific case. But there are situations
                      where it makes a difference.

                      Consider a class which holds a constant. To give this
                      constant a value you can onyl use initialization, not
                      assignement.

                      So:

                      ....
                      private:
                      const int value;
                      ....

                      public:
                      C( int Init ) : value( Init ) {}
                      ....

                      works (because the above is initialization and a constant can be
                      initialized), while

                      C( int Init ) { value = Init; }

                      will not work, because you cannot assign anything to a constant.

                      There are other cases too, where it is important to use an initializer
                      list. Consult your text book about those.

                      --
                      Karl Heinz Buchegger
                      kbuchegg@gascad .at

                      Comment

                      • David Harmon

                        #12
                        Re: Two questions about...somethi ng

                        On Mon, 02 Feb 2004 15:47:16 GMT in comp.lang.c++, Fred H
                        <secret@nospam. com> was alleged to have written:[color=blue]
                        >I have read the FAQ, and I search it quite often. But this time
                        >I didn't know what to search for. Now I know that I could have
                        >searched for "initializaion" ,[/color]

                        Even though I flog the FAQ too, I agree with you completely in this
                        case. It is hidden like an Easter egg if you do not know the name.
                        All you can do is memorize the whole FAQ... learn Stroustrup while you
                        are at it.

                        Please do not take FAQ pointers as meaning that you should not post.
                        Rather, we hope that having the FAQ might reduce the need to do so in
                        every case.

                        Comment

                        • Victor Bazarov

                          #13
                          Re: Two questions about...somethi ng

                          "Fred H" <secret@nospam. com> wrote...[color=blue]
                          > [...]
                          > But I still can't see why people like you allways need to tell people
                          > like me, that we really ought not to post in this group.[/color]

                          I never tell anybody not to post. It's simply not my place to tell
                          people what to do. However, when you post, you ask for advice and
                          invite comment. If you're not prepared to read any reasonable comment
                          to your post, you should refrain from posting, that's all.
                          [color=blue]
                          > What kind of activities is it you'd like there to be in this group,
                          > if newbies just isn't allowed here? I allways thought that
                          > comp.lang.c++.m oderated was the newbie free zone around here...[/color]

                          Around here? comp.lang.c++.m oderated is a different newsgroup. It
                          has its own rules, written or not, its own frequents, and I assure
                          you, it just as much welcomes newbies as this one (no less, no more).

                          If you do feel you need to attend a kindergarten first (judging by
                          your inability to exist in the real world without crying at the first
                          sign of flame or criticism), visit alt.comp.lang.l earn.c-c++

                          Good luck!

                          And don't forget to read the entire FAQ before EVER posting here again.


                          Comment

                          • Gianni Mariani

                            #14
                            Re: Two questions about...somethi ng

                            Fred H wrote:[color=blue]
                            >
                            > [Completely OT]
                            >[color=green]
                            >> This is covered in the FAQ. Please read FAQ before posting.
                            >>
                            >> I think you started reading the STL book too early. You need
                            >> a C++ book and enough time with it so you don't ask questions
                            >> like that.
                            >>
                            >> Victor[/color]
                            >
                            >
                            > I have read the FAQ, and I search it quite often. But this time
                            > I didn't know what to search for.[/color]

                            It's cool then. Yep - sometimes you just don't know the terminology and
                            you don't know what you're looking for.

                            Comment

                            • Fred H

                              #15
                              Re: Two questions about...somethi ng

                              [color=blue]
                              > If you do feel you need to attend a kindergarten first (judging by
                              > your inability to exist in the real world without crying at the first
                              > sign of flame or criticism), visit alt.comp.lang.l earn.c-c++[/color]

                              I'm sure we can coexist...in the real world. No need for kindergarten
                              for any of us I hope ;)

                              [color=blue]
                              > And don't forget to read the entire FAQ before EVER posting here again.[/color]

                              :D

                              --
                              Fred H

                              void FredH::Contact( ) {
                              TextToSpeach.sa y("frode at age dee dee dot en oh");
                              }

                              Comment

                              Working...