Variable initialization

F

Fokko Beekhof

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
 
V

Victor Bazarov

Fokko said:
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
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top