class object initialisation

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

    class object initialisation

    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


  • Ivan Vecerina

    #2
    Re: class object initialisation

    "A" <A@iprimus.com. au> wrote in message
    news:3f61b50b_1 @news.iprimus.c om.au...
    | 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?

    Only when you are unable to, e.g. when a complex computation involving
    several intermediate variables is needed and a dedicated function doesn't
    make sense.

    IMO the initialization list should always be preferred.


    Regards,
    --
    Ivan Vecerina - expert in medical devices, software - info, links, contact information, code snippets



    Comment

    • jeffc

      #3
      Re: class object initialisation


      "A" <A@iprimus.com. au> wrote in message
      news:3f61b50b_1 @news.iprimus.c om.au...[color=blue]
      > Hi,
      >
      > I have always been taught to use an inialization list for initialising[/color]
      data[color=blue]
      > members of a class. I realize that initialsizing primitives and pointers[/color]
      use[color=blue]
      > 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?[/color]

      The basic rule of thumb is that anything that can go in the initialize list
      should go there. Obviously, you can't put something like this in there:
      if (a)
      i = 2;
      else
      i = 4;


      Comment

      • Erik

        #4
        Re: class object initialisation

        > > Hi,[color=blue][color=green]
        > >
        > > I have always been taught to use an inialization list for initialising[/color]
        > data[color=green]
        > > members of a class. I realize that initialsizing primitives and pointers[/color]
        > use[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?[/color]
        >
        > The basic rule of thumb is that anything that can go in the initialize[/color]
        list[color=blue]
        > should go there. Obviously, you can't put something like this in there:
        > if (a)
        > i = 2;
        > else
        > i = 4;[/color]

        Many, if not most, of those cases can be covered by the ?: operator:
        MyClass(int a) : i(a ? 2 : 4) {}

        / Erik


        Comment

        • Gianni Mariani

          #5
          Re: class object initialisation

          Erik wrote:
          ....[color=blue][color=green]
          >>should go there. Obviously, you can't put something like this in there:
          >>if (a)
          >> i = 2;
          >>else
          >> i = 4;[/color]
          >
          >
          > Many, if not most, of those cases can be covered by the ?: operator:
          > MyClass(int a) : i(a ? 2 : 4) {}
          >[/color]

          Yep - and sometimes it makes sense to create a function that does more
          complex things so that everything is in the initializer list.

          Comment

          • jeffc

            #6
            Re: class object initialisation


            "Gianni Mariani" <gi2nospam@mari ani.ws> wrote in message
            news:bjsqne$oou @dispatch.conce ntric.net...[color=blue]
            > Erik wrote:
            > ...[color=green][color=darkred]
            > >>should go there. Obviously, you can't put something like this in there:
            > >>if (a)
            > >> i = 2;
            > >>else
            > >> i = 4;[/color]
            > >
            > >
            > > Many, if not most, of those cases can be covered by the ?: operator:
            > > MyClass(int a) : i(a ? 2 : 4) {}
            > >[/color]
            >
            > Yep - and sometimes it makes sense to create a function that does more
            > complex things so that everything is in the initializer list.[/color]

            And how exactly do you propose calling such a function from the initializer
            list?


            Comment

            • jeffc

              #7
              Re: class object initialisation


              "Erik" <no@spam.com> wrote in message news:bjspcn$r22 $1@news.lth.se. ..[color=blue][color=green]
              > > The basic rule of thumb is that anything that can go in the initialize[/color]
              > list[color=green]
              > > should go there. Obviously, you can't put something like this in there:
              > > if (a)
              > > i = 2;
              > > else
              > > i = 4;[/color]
              >
              > Many, if not most, of those cases can be covered by the ?: operator:
              > MyClass(int a) : i(a ? 2 : 4) {}[/color]

              Yeah, maybe simple "if" cases like that, but you can't put logic or function
              calls (other than base class constructors) in the initializer list. You
              added an expression, not a statement.


              Comment

              • Ron Natalie

                #8
                Re: class object initialisation


                "jeffc" <nobody@nowhere .com> wrote in message news:3f622ea6_1 @news1.prserv.n et...[color=blue]
                >[/color]
                [color=blue][color=green]
                > > Yep - and sometimes it makes sense to create a function that does more
                > > complex things so that everything is in the initializer list.[/color]
                >
                > And how exactly do you propose calling such a function from the initializer
                > list?[/color]

                Same way you call any other function. It behooves you not to use the
                yet uninitialized parts of the object being constructed though.


                Comment

                • Ron Natalie

                  #9
                  Re: class object initialisation


                  "jeffc" <nobody@nowhere .com> wrote in message news:3f622fa7_4 @news1.prserv.n et...
                  [color=blue][color=green]
                  > > Many, if not most, of those cases can be covered by the ?: operator:
                  > > MyClass(int a) : i(a ? 2 : 4) {}[/color]
                  >
                  > Yeah, maybe simple "if" cases like that, but you can't put logic or function
                  > calls (other than base class constructors) in the initializer list. You
                  > added an expression, not a statement.[/color]

                  Who says you can't have function calls?


                  Comment

                  • Kevin Goodsell

                    #10
                    Re: class object initialisation

                    Ying Yang wrote:
                    [color=blue][color=green]
                    >>
                    >>Never.
                    >>Initializatio n 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]

                    No, you cannot initialize anything with an assignment operator ever.
                    Assignment operators assign, they don't initialize. If you don't the
                    difference, you should look it up.

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

                    Comment

                    • Shane Beasley

                      #11
                      Re: class object initialisation

                      Kevin Goodsell <usenet1.spamfr ee.fusion@never box.com> wrote in message news:<7tv8b.918 $UN4.802@newsre ad3.news.pas.ea rthlink.net>...
                      [color=blue][color=green]
                      > > 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][/color]

                      (NB: This is true for all POD types, not just primitive types.)
                      [color=blue]
                      > No, you cannot initialize anything with an assignment operator ever.
                      > Assignment operators assign, they don't initialize. If you don't the
                      > difference, you should look it up.[/color]

                      int n; // n is not initialized
                      n = 0; // 0 assigned to n

                      Using an uninitialized lvalue as an rvalue is undefined (4.1/1). If
                      assignment doesn't initialize, ever, then

                      printf("%d\n", n);

                      results in undefined behavior. I, for one, highly doubt that.

                      - Shane

                      Comment

                      • Kevin Goodsell

                        #12
                        Re: class object initialisation

                        Shane Beasley wrote:
                        [color=blue]
                        >
                        >
                        > int n; // n is not initialized
                        > n = 0; // 0 assigned to n
                        >
                        > Using an uninitialized lvalue as an rvalue is undefined (4.1/1).[/color]

                        Using an indeterminate lvalue is undefined. "Uninitiali zed" is used to
                        mean "indetermin ate" sometimes, apparently even in the standard.
                        [color=blue]
                        > If
                        > assignment doesn't initialize, ever, then[/color]

                        It doesn't. It assigns.
                        [color=blue]
                        >
                        > printf("%d\n", n);
                        >
                        > results in undefined behavior. I, for one, highly doubt that.[/color]

                        The value is not indeterminate at this point.

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

                        Comment

                        • A

                          #13
                          Re: class object initialisation

                          [color=blue]
                          > Ying Yang wrote:
                          >[color=green][color=darkred]
                          > >>
                          > >>Never.
                          > >>Initializatio n 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[/color][/color]
                          using[color=blue][color=green]
                          > > an initialization list.[/color]
                          >
                          > No, you cannot initialize anything with an assignment operator ever.
                          > Assignment operators assign, they don't initialize. If you don't the
                          > difference, you should look it up.[/color]

                          To initialize means you give a variable it's initial value. An assignment
                          operator can be used to give a variable it's initial value, 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 data
                          members via two of the following ways: assignment or an initialisation list.
                          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.






                          Comment

                          • Kevin Goodsell

                            #14
                            Re: class object initialisation

                            A wrote:
                            [color=blue]
                            >
                            > To initialize means you give a variable it's initial value.[/color]

                            Agreed.
                            [color=blue]
                            > 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=blue]
                            > 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 data
                            > 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=blue]
                            > assignment or an initialisation list.[/color]

                            ....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=blue]
                            > 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]

                            Initialization happens when an object is initially constructed.
                            Assignment can only happen after that time (or not at all, for certain
                            types of objects).

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

                            Comment

                            • foo

                              #15
                              Re: class object initialisation

                              "jeffc" <nobody@nowhere .com> wrote in message news:<3f622fa7_ 4@news1.prserv. net>...[color=blue]
                              > "Erik" <no@spam.com> wrote in message news:bjspcn$r22 $1@news.lth.se. ..[color=green][color=darkred]
                              > > > The basic rule of thumb is that anything that can go in the initialize[/color][/color]
                              > list[color=green][color=darkred]
                              > > > should go there. Obviously, you can't put something like this in there:
                              > > > if (a)
                              > > > i = 2;
                              > > > else
                              > > > i = 4;[/color]
                              > >
                              > > Many, if not most, of those cases can be covered by the ?: operator:
                              > > MyClass(int a) : i(a ? 2 : 4) {}[/color]
                              >
                              > Yeah, maybe simple "if" cases like that, but you can't put logic or function
                              > calls (other than base class constructors) in the initializer list. You
                              > added an expression, not a statement.[/color]
                              There are plenty of things you can put in the initializer list.
                              You can put functions, additions, conditon logic, and more.
                              Example:

                              class foo
                              {
                              public:
                              foo(int x, const std::string &Src)
                              :m_i((x > 3)?Func2(8):x),
                              m_data((Src == "test")?Func1(" good"):Func1(Sr c)+" test"),
                              i(m_i)
                              {
                              }

                              private:
                              std::string Func1(const std::string &Src){return "Hello World " + Src;}
                              int Func2(int y){return y + 44;}
                              int m_i;
                              public:
                              const std::string m_data;//Needs to be in an initialized list
                              const int &i; //Needs to be in an initialized list
                              };

                              int main(int argc, char* argv[])
                              {
                              foo myfoo(2, "bla bla");
                              cout << myfoo.m_data << endl;
                              cout << myfoo.i << endl;

                              system("pause") ;
                              return 0;
                              }

                              Comment

                              Working...