468,758 Members | 2,073 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 468,758 developers. It's quick & easy.

Initialization via ctor vs. initialization via assignment

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
2 1450
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
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.

Similar topics

5 posts views Thread by Michael McKnerney | last post: by
5 posts views Thread by john sun | last post: by
50 posts views Thread by Charles Stapleton | last post: by
17 posts views Thread by Thomas Lorenz | last post: by
5 posts views Thread by Grahamo | last post: by
2 posts views Thread by timlyee | last post: by
16 posts views Thread by subramanian100in | last post: by
11 posts views Thread by subramanian100in | last post: by
1 post views Thread by CARIGAR | last post: by
reply views Thread by zhoujie | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.