473,395 Members | 2,436 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

Why is not copy constructor called?


Consider the code below. The output is the following two lines:

0xbfc78090
0xbfc780a0

This proves that the variable m in main() is not the very same instance
of MyClass as temp_m in hello(). Hence (?) m is created as copy of
temp_m. But the copy constructor is not called. Contradiction. Where am
I thinking incorrectly?

#include <iostream>

using namespace std;

class MyClass
{
public:
MyClass () {}

MyClass (const MyClass& m)
{
cout << "Copy constructor called!" << endl;
}
};

MyClass hello()
{
MyClass temp_m;
cout << &temp_m << endl;
return temp_m;
}

int main()
{
MyClass m;
m=hello();
cout << &m <<endl;
}

Oct 13 '06 #1
9 1659
ja****@gmail.com wrote:
Consider the code below. The output is the following two lines:

0xbfc78090
0xbfc780a0

This proves that the variable m in main() is not the very same instance
of MyClass as temp_m in hello(). Hence (?) m is created as copy of
temp_m. But the copy constructor is not called. Contradiction. Where am
I thinking incorrectly?
m is not created as a copy of temp_m. It is default constructed, and
only later is it assigned to the (temporary) return value of hello(),
using the compiler-generated assignment operator. To see this, add the
following to your class definition:

MyClass &operator=(const MyClass& m)
{
cout << "Assignment operator called!" << endl;
return *this;
}

You will see that it is being called. Alternatively, try:

MyClass m(hello());

and you will see the results you probably expected the first time
around.

Oct 13 '06 #2
IR
ja***@gmail.com wrote:
This proves that the variable m in main() is not the very same
instance of MyClass as temp_m in hello(). Hence (?) m is created
as copy of temp_m. But the copy constructor is not called.
Contradiction. Where am I thinking incorrectly?
m=hello();
You are not using the copy constructor, but the assignment operator.

Try defining in MyClass

MyClass& operator =(const MyClass& m)
{
cout << "Assignment operator called!" << endl;
}

OR in main() (to use copy constructor) :

MyClass m(hello());

Cheers,

--
IR
Oct 13 '06 #3
IR
IR wrote:
MyClass& operator =(const MyClass& m)
{
cout << "Assignment operator called!" << endl;
}
dammit i forgot return *this;
shame on me

--
IR
Oct 13 '06 #4
The code below should not call copy constructor.

Let's consider you main() again:

int main()
{
MyClass m; //here you construct an instance of MyClass - m
//the default constructor is used

//here you first call hello() which constructs another instance of
MyClass (temp_m)
//using the default constructor and returns it. The compiler would
usually avoid constructing
//a temporary MyClass object to be returned.
//
//next step is to assign the return value from hello() to m
//compiler would use the assignment operator rather then copy
constructor in this case
m=hello();

On Oct 13, 6:29 pm, jan...@gmail.com wrote:
Consider the code below. The output is the following two lines:

0xbfc78090
0xbfc780a0

This proves that the variable m in main() is not the very same instance
of MyClass as temp_m in hello(). Hence (?) m is created as copy of
temp_m. But the copy constructor is not called. Contradiction. Where am
I thinking incorrectly?

#include <iostream>

using namespace std;

class MyClass
{
public:
MyClass () {}

MyClass (const MyClass& m)
{
cout << "Copy constructor called!" << endl;
}

};MyClass hello()
{
MyClass temp_m;
cout << &temp_m << endl;
return temp_m;

}int main()
{
MyClass m;
m=hello();
cout << &m <<endl;

}- Hide quoted text -- Show quoted text -
Oct 13 '06 #5
* ja****@gmail.com:
Consider the code below. The output is the following two lines:

0xbfc78090
0xbfc780a0

This proves that the variable m in main() is not the very same instance
of MyClass as temp_m in hello(). Hence (?) m is created as copy of
temp_m. But the copy constructor is not called. Contradiction. Where am
I thinking incorrectly?

#include <iostream>

using namespace std;

class MyClass
{
public:
MyClass () {}

MyClass (const MyClass& m)
{
cout << "Copy constructor called!" << endl;
}
};

MyClass hello()
{
MyClass temp_m;
cout << &temp_m << endl;
return temp_m;
}

int main()
{
MyClass m;
m=hello();
cout << &m <<endl;
}
Well, there are two possible misconceptions involved.

First, the '=' in the statement 'm=hello();' is an /assignment/,
invoking the assignment operator, not the copy constructor. The
difference between assignment and copy construction is that assignment
changes the member values of some existing object (perhaps deallocating
already allocated memory), whereas copy construction turns a chunk of
raw, uninitialized memory into an object, a copy. Perhaps you knew
that, but the formulation "creates as a copy of" seems to indicate that
this is indeed the basic misconception; if you'd written 'MyClass m =
hello();' then the "=" would instead denote copy construction.

Second, the compiler is allowed to optimize away copy construction in
certain situations, /regardless of whether the copy constructor has side
effects or not/. The copy constructor is very very special, in that the
compiler, in these relevant situations, is allowed to assume that what
the copy constructor does is to actually construct a perfect copy, and
nothing else whatsoever. These situations include the 'MyClass m =
hello();' initialization, as well as the call to 'hello()' itself (where
this optimization is known as RVO, Return Value Optimization).

This also means that C++ tests that ask you to count the number of copy
constructor calls in a piece of code, ending up with some exact number,
are generally tests made by incompetents (although in some pieces of
code you can be sure of the number of calls).

And unfortunately that includes most C++ tests, even some that cost $$$.

Hth.,

- Alf
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Oct 13 '06 #6
IR
Alf P. Steinbach wrote:
if you'd written 'MyClass m = hello();' then
the "=" would instead denote copy construction.
Interesting... I believe I once read an article on this topic, which
conclusion (as far a I recall) was:

Always use explicit copy construction
MyClass m(hello());
rather than assignment
MyClass m = hello();
as the latter translates to
MyClass m; m = hello();
which obviously calls an useless default constructor.

Alf (or anyone else), could you shed some light on this? Your
statement kinda confuses me, is this explicitely part of the standard?

Thanks in advance.

--
IR
Oct 13 '06 #7
* IR:
Alf P. Steinbach wrote:
>if you'd written 'MyClass m = hello();' then
the "=" would instead denote copy construction.

Interesting... I believe I once read an article on this topic, which
conclusion (as far a I recall) was:

Always use explicit copy construction
MyClass m(hello());
rather than assignment
MyClass m = hello();
as the latter translates to
MyClass m; m = hello();
which obviously calls an useless default constructor.

Alf (or anyone else), could you shed some light on this?
Yes, I did. ;-)

An initialization with "=" is formally a copy initialization, using the
copy constructor (which call can, however, be optimized away).

It's not translated to default construction plus assignment: a compiler
that did that (none such exist as far as I know) would be in flagrant
breach of the rules of the standard.

Your
statement kinda confuses me, is this explicitely part of the standard?
Yes.

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Oct 13 '06 #8
IR
Alf P. Steinbach wrote:
An initialization with "=" is formally a copy initialization,
using the copy constructor (which call can, however, be optimized
away).

It's not translated to default construction plus assignment: a
compiler that did that (none such exist as far as I know) would be
in flagrant breach of the rules of the standard.
Oh well, I just tested it in VS8. You are right (of course).

So, either the author of the article was wrong, or I have the memory
of a goldfish (which is the most likely of the two alternatives...)

In other words, my bad.
At least I'll have learned something today :-)

--
IR
Oct 13 '06 #9
* IR:
>
[...], or I have the memory
of a goldfish (which is the most likely of the two alternatives...)
See e.g. <url: http://www.abc.net.au/science/k2/moments/s1179348.htm>:
<quote>
The fish that knew their tank remembered the trawling net so well,
that they could escape it in a follow-up study some 11 months later.

By the way, 11 months is nearly one third of his fish's 3-year
lifespan. That's a very long time to remember something that has
happened to you only once, and in human terms, about 25 years ago.

Yoichi Oda of Osaka University in Japan has spent years studying the
fine details of memory in goldfish - and he's also convinced that
goldfish have a good memory.
</quote>

See also e.g. Yahoo! Answers "How intelligent are goldfish?" at <url:
http://uk.answers.yahoo.com/question/index?qid=20061005044222AA8AcA0>:
<quote>
Goldfish and the 3 second memory span:
The Myth Busters TV show proved this one a myth. They taught fish to
swim through a maze, showing that their time got faster and faster.
Thus proving they remembered where the holes were.
</quote>

Thus, in conclusion, if you actually have the memory (that would be
analogous to the memory) of a goldfish, then you have a very good memory
indeed, able to remember trivial details a third of a lifespan later.

Anyway, let's stop the goldfish bashing in clc++!

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Oct 13 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

42
by: Edward Diener | last post by:
Coming from the C++ world I can not understand the reason why copy constructors are not used in the .NET framework. A copy constructor creates an object from a copy of another object of the same...
15
by: A | last post by:
Hi, A default copy constructor is created for you when you don't specify one yourself. In such case, the default copy constructor will simply do a bitwise copy for primitives (including...
4
by: Kench | last post by:
Sorry if this becomes a repost. I posted this to comp.lang.c++.moderated 1 hour ago still it does not show up there so posting this here. Hi, Consider class A & B both of which implement a copy...
14
by: trying_to_learn | last post by:
i am on the chapter on copy construction in C++ in the code (see below), the author says if u pass the object by value as in HowMany h2 = f(h); ....then a bitwise object is created w/o calling...
8
by: trying_to_learn | last post by:
Why do we need to explicitly call the copy constructor and the operator = , for base class and member objects in composition? ....book says "You must explicitly call the GameBoard copy-constructor...
3
by: bipod.rafique | last post by:
Hello all, Even though this topic has been discussed many times, I still need your help in clearing my confusions. Consider the following code: class aclass{ public: aclass(){
4
by: Tony Johansson | last post by:
Hello Experts! I have this constructor for class Flight. Flight::Flight(string flight_no, Klocka dep_t, Klocka arr_t) : no(flight_no), dep(dep_t), arr(arr_t) {} Both dep and arr are...
7
by: vj | last post by:
Hi! I recently came across this intresting behaviour shown by Visual C++ 6.0 compiler regarding Copy Constructors. Please tell me that is this the standard behaviour shown by all compilers or its...
7
by: skishorev | last post by:
Hi, I know What is the copy constructor. I don't know where and why we have to use copy constructor. If You know please give to me with a situation where we have to use or with a small example....
6
by: suresh | last post by:
Hi Could you please tell why copy constructor is not called in the first line in main(), as mentioned in the text books. I used g++ version 4.1.2 on debian etch thanks suresh # include...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.