Variable initialization

Discussion in 'C++' started by Fokko Beekhof, Feb 7, 2008.

  1. Hello,

    If a variable is declared and initialized, that can be done with an
    assignment:
    Foo bar = otherFoo;
    or with a constructor:
    Foo bar((otherFoo));

    Which one is preferable ? I would guess by "constructor", because
    otherwise the object would first be constructed, and then be copied
    over, which is more work than constructing it after a given object in
    the first place.

    I guess that for basic type (int, double, etc. ) there is not much
    difference, but for classes with a non-trivial copy-constructor and
    assignment operator, it might make a difference.

    Is that reasoning correct ?

    Thanks in advance,

    FPB
    Fokko Beekhof, Feb 7, 2008
    #1
    1. Advertising

  2. Fokko Beekhof wrote:
    > If a variable is declared and initialized, that can be done with an
    > assignment:
    > Foo bar = otherFoo;
    > or with a constructor:
    > Foo bar((otherFoo));
    >
    > Which one is preferable ? I would guess by "constructor", because
    > otherwise the object would first be constructed, and then be copied
    > over, which is more work than constructing it after a given object in
    > the first place.


    If the type of the 'otherFoo' is also 'Foo', it does not matter. The
    semantics of the initialisation are exactly the same.

    > I guess that for basic type (int, double, etc. ) there is not much
    > difference, but for classes with a non-trivial copy-constructor and
    > assignment operator, it might make a difference.
    >
    > Is that reasoning correct ?


    No. The assignment operator is not used for the initialisation (no
    matter that they share the symbol, '='). The assignment operator is
    only used for _assignment_.

    V
    --
    Please remove capital 'A's when replying by e-mail
    I do not respond to top-posted replies, please don't ask
    Victor Bazarov, Feb 7, 2008
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. JKop
    Replies:
    10
    Views:
    926
  2. Matthias Kaeppler
    Replies:
    2
    Views:
    431
    Victor Bazarov
    Jul 18, 2005
  3. Replies:
    6
    Views:
    451
    Ron Natalie
    Dec 11, 2005
  4. toton
    Replies:
    5
    Views:
    920
    Victor Bazarov
    Sep 28, 2006
  5. Jess
    Replies:
    23
    Views:
    915
Loading...

Share This Page