class object initialisation

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

    #16
    Re: class object initialisation

    "A" <A@iprimus.com. au> wrote in message news:<3f61b50b_ 1@news.iprimus. com.au>...[color=blue]
    > Hi,
    >
    > I have always been taught to use an inialization list for initialising data
    > members of a class. I realize that initialsizing primitives and pointers use
    > an inialization list is exactly the same as an assignment, but for class
    > types it has a different effect - it calls the copy constructor.
    >
    > My question is when to not use an initalisation list for initialising data
    > members of a class?
    >
    >
    > Regards
    > Adi
    >
    >
    >
    > ---
    > Outgoing mail is certified Virus Free.
    > Checked by AVG anti-virus system (http://www.grisoft.com).
    > Version: 6.0.516 / Virus Database: 313 - Release Date: 1/09/2003[/color]

    You need to have an item in the initialize list if it's a constant or
    a reference data member.
    You also need to have the base class constructor in the initializer
    list if the base class does not have a default contructor.

    I recommend that you always TRY to use the initialize list.

    An initializer list may not be appropriate when you have multiple
    constructors, and serveral member variables that have common
    initialization values with all the constructors.
    In such cases, it's common to create an function initializer to
    consolidate the logic.
    Example:
    class car
    {
    public:
    car(){Initializ e();}
    car(int x){Initialize() ;}
    car(const char* s){Initialize() ;}
    inline void Initialize()
    {
    QtyWheels = 4;
    ID = -1;
    Make = "n/a";
    }
    private:
    int QtyWheels;
    int ID;
    std::string Make;
    };

    Comment

    • Shane Beasley

      #17
      Re: class object initialisation

      Kevin Goodsell <usenet1.spamfr ee.fusion@never box.com> wrote in message news:<LRI8b.186 3$UN4.213@newsr ead3.news.pas.e arthlink.net>.. .
      [color=blue]
      > Using an indeterminate lvalue is undefined. "Uninitiali zed" is used to
      > mean "indetermin ate" sometimes, apparently even in the standard.[/color]

      "Apparently "? You make it sound like you know the terminology better
      than the authors of the standard. Regardless, they chose to use
      "initialization " to describe both syntax (direct- and
      copy-initialization) and semantics (the act of giving a variable its
      first value, even through assignment), and so that's what it means.

      - Shane

      Comment

      • Kevin Goodsell

        #18
        Re: class object initialisation

        Shane Beasley wrote:[color=blue]
        > Kevin Goodsell <usenet1.spamfr ee.fusion@never box.com> wrote in message news:<LRI8b.186 3$UN4.213@newsr ead3.news.pas.e arthlink.net>.. .
        >
        >[color=green]
        >>Using an indeterminate lvalue is undefined. "Uninitiali zed" is used to
        >>mean "indetermin ate" sometimes, apparently even in the standard.[/color]
        >
        >
        > "Apparently "? You make it sound like you know the terminology better
        > than the authors of the standard. Regardless, they chose to use
        > "initialization " to describe both syntax (direct- and
        > copy-initialization) and semantics (the act of giving a variable its
        > first value, even through assignment), and so that's what it means.[/color]

        Please show me where in the standard this definition is given.

        I know what the intent of the language in the standard is. The
        difference between initialization and assignment has been frequently
        pointed out by people who helped write the standard, not to mention
        Stroustrup himself:

        initialization - giving an object an initial value. Initialization
        differs from assignment in that there is no previous value involved.
        Initialization is done by constructors.


        So, do you know the terminology better than Bjarne Stroustrup?

        -Kevin
        --
        My email address is valid, but changes periodically.
        To contact me please use the address from a recent posting.

        Comment

        • Shane Beasley

          #19
          Re: class object initialisation

          Kevin Goodsell <usenet1.spamfr ee.fusion@never box.com> wrote in message news:<dw19b.327 4$BS5.2819@news read4.news.pas. earthlink.net>. ..
          [color=blue]
          > Please show me where in the standard this definition is given.[/color]

          As previously quoted, 4.1/1 clearly states that an lvalue may not be
          used as an rvalue unless it was previously initialized. Apparently,

          int n;
          n = 0;

          qualifies as initialization for these purposes. But it's not done via
          direct- or copy-initialization syntax in the declaration of n; rather,
          it's done via an assignment expression, so called because it performs
          assignment.
          [color=blue]
          > I know what the intent of the language in the standard is. The
          > difference between initialization and assignment has been frequently
          > pointed out by people who helped write the standard, not to mention
          > Stroustrup himself:
          >
          >
          > initialization - giving an object an initial value. Initialization
          > differs from assignment in that there is no previous value involved.
          > Initialization is done by constructors.
          >
          >
          > http://www.research.att.com/~bs/glossary.html
          >
          > So, do you know the terminology better than Bjarne Stroustrup?[/color]

          I know that PODs aren't initialized by constructor (indeed, they
          needn't be initialized at all, useless as that would be). Short of
          saying that he's wrong, my guess is that he's talking about non-PODs,
          which accounts for most types (excluding pointers), and about which
          he's entirely correct.

          As for PODs, consider the following:

          // Assign n to x. (That *is* what it does, no?)
          template <typename T> void assign (T &x, T n) { x = n; }

          int main () {
          int i = 0, j;
          assign(i, 0);
          assign(j, 0);
          i = j;
          }

          If you're right, then either j isn't initialized and this program is
          undefined by 4.1/1, or assign(x, n) performs assignment sometimes and
          initialization other times -- all with the same code. (It could also
          use a better name -- assign_or_initi alize, maybe.) More likely,
          assign(x, n) performs assignment all the time and initialization
          sometimes.

          You're free to disagree, I guess. Of course, it doesn't matter what
          your opinion (or mine) is; neither of us will learn anything about C++
          that we didn't already know before this thread, nor do I think that
          either of us will convince the other of his point. To quote somebody:

          "Arguing on the Internet is like competing in the Special Olympics...
          Even if you win, you're still retarded."

          With that, I hereby agree to disagree and resign.

          - Shane

          Comment

          • Kevin Goodsell

            #20
            Re: class object initialisation

            Shane Beasley wrote:[color=blue]
            > Kevin Goodsell <usenet1.spamfr ee.fusion@never box.com> wrote in message news:<dw19b.327 4$BS5.2819@news read4.news.pas. earthlink.net>. ..
            >
            >[color=green]
            >>Please show me where in the standard this definition is given.[/color]
            >
            >
            > As previously quoted, 4.1/1 clearly states that an lvalue may not be
            > used as an rvalue unless it was previously initialized. Apparently,[/color]

            No, it says it can't if the object to which the lvalue refers is
            "uninitialized" . I can't find a definition for that term in the
            standard, but I think it's fairly clear that in this context they are
            using it to mean "having an indeterminate value". This use of this term
            here may be a defect. In my opinion, it's very clear in the standard
            itself that "initialization " refers to giving a value to an object when
            it is created.
            [color=blue]
            >
            > int n;
            > n = 0;
            >
            > qualifies as initialization for these purposes.[/color]

            It qualifies as giving it a determinate value, but initialization only
            occurs when an object is created.
            [color=blue][color=green]
            >>
            >>
            >>initializatio n - giving an object an initial value. Initialization
            >>differs from assignment in that there is no previous value involved.
            >>Initializatio n is done by constructors.
            >>
            >>
            >>http://www.research.att.com/~bs/glossary.html
            >>
            >>So, do you know the terminology better than Bjarne Stroustrup?[/color]
            >
            >
            > I know that PODs aren't initialized by constructor (indeed, they
            > needn't be initialized at all, useless as that would be).[/color]

            Stroustrup seems to be of the opinion that all types have constructors
            (though the standard disagrees with him). I believe this has been
            discussed here before. See, for example, page 131 of TC++PL3. I think he
            was referring to all types here.
            [color=blue]
            > Short of
            > saying that he's wrong, my guess is that he's talking about non-PODs,
            > which accounts for most types (excluding pointers), and about which
            > he's entirely correct.
            >
            > As for PODs, consider the following:
            >
            > // Assign n to x. (That *is* what it does, no?)
            > template <typename T> void assign (T &x, T n) { x = n; }
            >
            > int main () {
            > int i = 0, j;
            > assign(i, 0);
            > assign(j, 0);
            > i = j;
            > }
            >
            > If you're right, then either j isn't initialized and this program is
            > undefined by 4.1/1, or assign(x, n) performs assignment sometimes and
            > initialization other times -- all with the same code.[/color]

            I don't see where you are getting that from. The function clearly does
            an assignment. 4.1/1 deals with conversion from an lvalue to an rvalue,
            which does not apply in this case. See 8.5.3/5-7:

            5 A reference to type "cv1 T1" is initialized by an expression of type
            "cv2 T2" as follows:

            --If the initializer expression

            6
            --is an lvalue (but not an lvalue for a bit-field), and "cv1 T1" is
            reference-compatible with "cv2 T2," or

            --has a class type (i.e., T2 is a class type) and can be implicitly

            converted to an lvalue of type "cv3 T3," where "cv1 T1" is refer-
            ence-compatible with "cv3 T3" 9) (this conversion is selected by
            enumerating the applicable conversion functions (_over.match.re f_)
            and choosing the best one through overload resolution
            (_over.match_)) , then

            7 the reference is bound directly to the initializer expression lvalue
            in the first case, and the reference is bound to the lvalue result
            of the conversion in the second case. In these cases the reference
            is said to bind directly to the initializer expression. [Note: the
            usual lvalue-to-rvalue (_conv.lval_), array-to-pointer
            (_conv.array_), and function-to-pointer (_conv.func_) standard con-
            versions are not needed, and therefore are suppressed, when such
            direct bindings to lvalues are done. ]


            Summarized, when initializing (e.g., through function argument passing)
            a reference, if the initializer expression is a lvalue (clearly the case
            here) that is reference-compatible with the destination reference type
            (also applicable here), the reference is bound directly to the lvalue,
            and the usual lvalue-to-rvalue conversion is suppressed. If you need
            proof that function argument passing qualifies as initialization, please
            see 8.5/1
            [color=blue]
            > (It could also
            > use a better name -- assign_or_initi alize, maybe.) More likely,
            > assign(x, n) performs assignment all the time and initialization
            > sometimes.
            >
            > You're free to disagree, I guess. Of course, it doesn't matter what
            > your opinion (or mine) is; neither of us will learn anything about C++
            > that we didn't already know before this thread, nor do I think that
            > either of us will convince the other of his point. To quote somebody:
            >
            > "Arguing on the Internet is like competing in the Special Olympics...
            > Even if you win, you're still retarded."[/color]

            Well, for one thing neither of us is going to win. Which is pretty much
            what you said above.
            [color=blue]
            >
            > With that, I hereby agree to disagree and resign.[/color]

            That's a bit premature. Here are a few more quotations to emphasize my
            point (that the intent of the standard, if not the precise wording, is
            that initialization occurs only at the time of creation):

            8.5 Initializers [dcl.init]

            1 A declarator can specify an initial value for the identifier being
            declared. The identifier designates an object or reference being ini-
            tialized. The process of initialization described in the remainder of
            _dcl.init_ applies also to initializations specified by other syntac-
            tic contexts, such as the initialization of function parameters with
            argument expressions (_expr.call_) or the initialization of return
            values (_stmt.return_) .

            The very fact that "Initialize rs" comes under declarations is a pretty
            strong statement about where initialization occurs, I think. The
            phrasing of this passage also implies that initialization is done at
            object creation.


            12.8 Copying class objects [class.copy]

            1 A class object can be copied in two ways, by initialization
            (_class.ctor_, _dcl.init_), including for function argument passing
            (_expr.call_) and for function value return (_stmt.return_) , and by
            assignment (_expr.ass_). Conceptually, these two operations are
            implemented by a copy constructor (_class.ctor_) and copy assignment
            operator (_over.ass_).


            This again shows the distinction between initialization and assignment
            (applied only to classes in this case).

            Maybe stronger proof is in there somewhere. I'm kind of tired of looking
            for it, though. I'll agree that the standard appears to be not entirely
            consistent on this point, but my feeling is that the intent of the
            standard is to create a logical distinction between initialization
            (which occurs when an object is created) and assignment (which can only
            occur when the target already exists).

            -Kevin
            --
            My email address is valid, but changes periodically.
            To contact me please use the address from a recent posting.

            Comment

            • Ying Yang

              #21
              Re: class object initialisation


              "Kevin Goodsell" <usenet1.spamfr ee.fusion@never box.com> wrote in message
              news:f6P8b.2536 $UN4.1551@newsr ead3.news.pas.e arthlink.net...[color=blue]
              > A wrote:
              >[color=green]
              > >
              > > To initialize means you give a variable it's initial value.[/color]
              >
              > Agreed.
              >[color=green]
              > > An assignment
              > > operator can be used to give a variable it's initial value,[/color]
              >
              > No, it can't. If you believe it can, please give an example.[/color]

              int i; //declared but not initialised
              i =5; // variable i is initialised with value 5.
              [color=blue][color=green]
              > > and it can also
              > > be used to re-assign a variable with a different value, providing the
              > > variable is not defined as constant. The point is, you can initialise[/color][/color]
              data[color=blue][color=green]
              > > members via two of the following ways:[/color]
              >
              > Well, you can't give something its initial value twice, so I assume you
              > mean "one of the following ways".[/color]

              what are you smoking?
              [color=blue]
              > ...But you're still wrong. Assignment does not give an initial value to
              > something. Assignment can only happen to an existing object. Since the
              > object must exist prior to the assignment, it clearly has already
              > received its initial value.[/color]

              Assignment can be used for both objects types and primitive types. And i was
              referring to initialising data members of a class type. Again, what are you
              smoking?
              [color=blue][color=green]
              > > However, the behaviour of the two is different depending whether is it a
              > > primitive or class type data member you want to initialize. If you don't
              > > agree with my definition of assignment and initialisation then I like to
              > > hear your definitions.[/color][/color]




              Comment

              • Ying Yang

                #22
                Re: class object initialisation

                > > Hi,[color=blue][color=green]
                > >
                > > I have always been taught to use an inialization list for initialising[/color][/color]
                data[color=blue][color=green]
                > > members of a class. I realize that initialsizing primitives and pointers[/color][/color]
                use[color=blue][color=green]
                > > an inialization list is exactly the same as an assignment, but for class
                > > types it has a different effect - it calls the copy constructor.
                > >
                > > My question is when to not use an initalisation list for initialising[/color][/color]
                data[color=blue][color=green]
                > > members of a class?
                > >
                > >
                > > Regards
                > > Adi[/color]
                >
                >
                > You need to have an item in the initialize list if it's a constant or
                > a reference data member.
                > You also need to have the base class constructor in the initializer
                > list if the base class does not have a default contructor.[/color]

                If my class does not extend any class then there would be no base class your
                referring to. Maybe you mean a default constructor of a class must always be
                present when you use an initialisation list. Can you be more clear?


                PPP


                Comment

                • Karl Heinz Buchegger

                  #23
                  Re: class object initialisation



                  Ying Yang wrote:[color=blue]
                  >[color=green]
                  > > A wrote:[color=darkred]
                  > > >
                  > > > Hi,
                  > > >
                  > > > I have always been taught to use an inialization list for initialising[/color][/color]
                  > data[color=green][color=darkred]
                  > > > members of a class. I realize that initialsizing primitives and pointers[/color][/color]
                  > use[color=green][color=darkred]
                  > > > an inialization list is exactly the same as an assignment, but for class
                  > > > types it has a different effect - it calls the copy constructor.[/color]
                  > >
                  > > No. It calls whatever constructor you specify in the initializer list.
                  > >[color=darkred]
                  > > >
                  > > > My question is when to not use an initalisation list for initialising[/color][/color]
                  > data[color=green][color=darkred]
                  > > > members of a class?[/color]
                  > >
                  > > Never.
                  > > Initialization lists are the only way to *initialize* members of a class
                  > > or to specify which constructor from a base class should be used.[/color]
                  >
                  > No, it's not the only way - as i mentioned you can use an assignment
                  > operator for initialising primitive data members, which is the same as using
                  > an initialization list.[/color]

                  But then it is no longer *initialization *.
                  It is assignment.

                  Those are different things.

                  --
                  Karl Heinz Buchegger
                  kbuchegg@gascad .at

                  Comment

                  • Karl Heinz Buchegger

                    #24
                    Re: class object initialisation



                    Ying Yang wrote:[color=blue]
                    >
                    >
                    > int i; //declared but not initialised[/color]

                    wrong. initialized to an undetermined value. Initialization.
                    [color=blue]
                    > i =5; // variable i is initialised with value 5.[/color]

                    replacing the undetermined value with a determined value. Assignment.

                    Initialization happens when a variable comes to live. Note: A variable
                    can also be initialized to an undetermined value! Once a variable
                    is 'alive', you can't initialize it any more. But of course you
                    can assign values to it (except in some cases, eg. references).

                    --
                    Karl Heinz Buchegger
                    kbuchegg@gascad .at

                    Comment

                    • Ying Yang

                      #25
                      Re: class object initialisation

                      > Ying Yang wrote:[color=blue][color=green]
                      > >
                      > >
                      > > int i; //declared but not initialised[/color]
                      >
                      > wrong. initialized to an undetermined value. Initialization.[/color]

                      disagree.

                      Initialization of an object or primitive means to give a determined value to
                      them for the first time.

                      [color=blue][color=green]
                      > > i =5; // variable i is initialised with value 5.[/color]
                      >
                      > replacing the undetermined value with a determined value. Assignment.
                      >
                      > Initialization happens when a variable comes to live. Note: A variable
                      > can also be initialized to an undetermined value! Once a variable
                      > is 'alive', you can't initialize it any more. But of course you
                      > can assign values to it (except in some cases, eg. references).[/color]

                      In light of the above, this is no longer valid.




                      Comment

                      • Attila Feher

                        #26
                        Re: class object initialisation

                        Karl Heinz Buchegger wrote:[color=blue]
                        > Ying Yang wrote:[color=green]
                        >>
                        >>
                        >> int i; //declared but not initialised[/color]
                        >
                        > wrong. initialized to an undetermined value. Initialization.[/color]


                        Wrong. This i, if it has an automatic storage, is not initialized.
                        Accessing it for anything else then writing (assigment or initialization) it
                        (well, reading it in any way) is undefined behavior.

                        --
                        Attila aka WW


                        Comment

                        • Karl Heinz Buchegger

                          #27
                          Re: class object initialisation



                          Attila Feher wrote:[color=blue]
                          >
                          > Karl Heinz Buchegger wrote:[color=green]
                          > > Ying Yang wrote:[color=darkred]
                          > >>
                          > >>
                          > >> int i; //declared but not initialised[/color]
                          > >
                          > > wrong. initialized to an undetermined value. Initialization.[/color]
                          >
                          > Wrong.[/color]

                          OK.
                          (it was just a wild guess, apologies for that).

                          This i, if it has an automatic storage, is not initialized.[color=blue]
                          > Accessing it for anything else then writing (assigment or initialization)[/color]

                          If it has not been initialized, how can it be initialized later?
                          I thought that initialization can only occour when a variable
                          is created. Afterwards it is always assignment.

                          --
                          Karl Heinz Buchegger
                          kbuchegg@gascad .at

                          Comment

                          • tom_usenet

                            #28
                            Re: class object initialisation

                            On Mon, 15 Sep 2003 20:41:24 +0930, "Ying Yang" <YingYang@hotma il.com>
                            wrote:
                            [color=blue][color=green]
                            >> Ying Yang wrote:[color=darkred]
                            >> >
                            >> >
                            >> > int i; //declared but not initialised[/color]
                            >>
                            >> wrong. initialized to an undetermined value. Initialization.[/color]
                            >
                            >disagree.
                            >
                            >Initializati on of an object or primitive means to give a determined value to
                            >them for the first time.[/color]

                            Your "definition " of initialization is at odds with the C++ standard:

                            "1 When no initializer is specified for an object of (possibly
                            cv­qualified) class type (or array thereof), or the
                            initializer has the form (), the object is initialized as specified in
                            8.5. [Note: if the class is a non­POD, it is
                            default­initial ized. ]"

                            Here's the bit in 8.5:
                            "9 If no initializer is specified for an object, and the object is of
                            (possibly cv­qualified) non­POD class type (or array thereof), the
                            object shall be default­initial ized; if the object is of
                            const­qualified type, the underlying class type shall have a
                            user­declared default constructor. Otherwise, if no initializer is
                            specified for an object, the object and its subobjects, if any, have
                            an indeterminate initial value;"

                            In other words, if you don't explicitly initialize an int (which is a
                            POD type), it is initialized with an indeterminate initial value.

                            Tom

                            Comment

                            • Attila Feher

                              #29
                              Re: class object initialisation

                              Karl Heinz Buchegger wrote:[color=blue]
                              > This i, if it has an automatic storage, is not initialized.[color=green]
                              >> Accessing it for anything else then writing (assigment or
                              >> initialization)[/color]
                              >
                              > If it has not been initialized, how can it be initialized later?
                              > I thought that initialization can only occour when a variable
                              > is created. Afterwards it is always assignment.[/color]

                              I was not clear. Of course it can only be assigned later on. Except of
                              course if someone is "clever enough" (remember! we talk about an int, POD)
                              and call placement new on its address. It would be an initialization,
                              although a pretty questionable one. :-)

                              --
                              Attila aka WW


                              Comment

                              • tom_usenet

                                #30
                                Re: class object initialisation

                                On 14 Sep 2003 19:07:41 -0700, sbeasley@cs.uic .edu (Shane Beasley)
                                wrote:
                                [color=blue]
                                >Kevin Goodsell <usenet1.spamfr ee.fusion@never box.com> wrote in message news:<dw19b.327 4$BS5.2819@news read4.news.pas. earthlink.net>. ..
                                >[color=green]
                                >> Please show me where in the standard this definition is given.[/color]
                                >
                                >As previously quoted, 4.1/1 clearly states that an lvalue may not be
                                >used as an rvalue unless it was previously initialized. Apparently,
                                >
                                > int n;
                                > n = 0;
                                >
                                >qualifies as initialization for these purposes. But it's not done via
                                >direct- or copy-initialization syntax in the declaration of n; rather,
                                >it's done via an assignment expression, so called because it performs
                                >assignment.[/color]

                                That is a defect in the standard. It should say "indetermin ate value":



                                The intent of the standard is clear: initialization and assignment are
                                not ever meant to mean the same thing.

                                Tom

                                Comment

                                Working...