By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
454,922 Members | 1,185 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 454,922 IT Pros & Developers. It's quick & easy.

Initialization via ctor vs. initialization via assignment

P: n/a
Hi,

say I have an arbitrary class Bar:

1 Bar a;
2 Bar b(a);
3 Bar c = a;

In line 3, is the default ctor called for c _first_ and _then_ the
assignment operator, or is c never default constructed and immediately
initialized with a?

My point is, for complex objects, is it likely that initialization via
assignment is less efficient than via constructor calls? What is the
recommended approach?

--
Matthias Kaeppler
Jul 23 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
Matthias Kaeppler wrote:
Hi,

say I have an arbitrary class Bar:

1 Bar a;
2 Bar b(a);
3 Bar c = a;

In line 3, is the default ctor called for c _first_ and _then_ the
assignment operator, or is c never default constructed and immediately
initialized with a?

My point is, for complex objects, is it likely that initialization via
assignment is less efficient than via constructor calls? What is the
recommended approach?


2 & 3 mean exactly the same thing. BTW, one way of answering this
questing is by writing a 30 liner like so.

#include <iostream>
#include <ostream>

struct A
{
A()
{
std::cout << "A default\n";
}

A( const A & )
{
std::cout << "A copy\n";
}

A & operator= ( const A & )
{
std::cout << "A operator =\n";
return * this;
}

};
int main()
{
std::cout << "A x;\n";
A x;

std::cout << "A y( x );\n";
A y( x );

std::cout << "A z = x;\n";
A z = x;
}
Jul 23 '05 #2

P: n/a
Matthias Kaeppler wrote:
say I have an arbitrary class Bar:

1 Bar a;
2 Bar b(a);
3 Bar c = a;

In line 3, is the default ctor called for c _first_ and _then_ the
assignment operator,
No.
or is c never default constructed and immediately
initialized with a?
'c' is constructed from 'a' via the copy c-tor. Since 'a' and 'c' are
of the same type, the case 3 is the same as the case 2.
My point is, for complex objects, is it likely that initialization via
assignment is less efficient than via constructor calls? What is the
recommended approach?


There is no assignment involved in construction (unless you make it so).

V
Jul 23 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.