473,804 Members | 2,272 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 1684
ja****@gmail.co m 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=(cons t 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.co m 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.co m:
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.yaho o.com/question/index?qid=20061 005044222AA8AcA 0>:
<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
5816
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 kind. It sounds simple but evidently .NET has difficulty with this concept for some reason. I do understand that .NET objects are created on the GC heap but that doesn't mean that they couldn't be copied from another object of the same kind when...
15
21206
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 pointers) and for objects types call their default constructor. Any others points i should know?
4
1628
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 constructor. class B inherits from A. When copy constructor of B is called, first the constructor of A gets called My question is that, why the copy constructor for A not called. Is there a way to have it call the copy constructor of class A?
14
1993
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 the constructor of the class. However he says when we leave scope of function HowMany f(HowMany x) then the destructor is called. why this inconsistency?. Accdng to me even the destructor should *not* be called. i can understand that bit wise copy...
8
2986
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 or the default constructor is automatically called instead" Why cant the compiler do this on its own. if we are making an object through copr construction for an inherited class , then why not simply call the corresponding copy constructors for...
3
2430
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
433
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 objects of the Klocka class in the definition of the Flight class.
7
1605
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 limited only to VC++. Listing 1 ================== #include <iostream> using namespace std;
7
2693
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. I am waiting for your reply. Thanks & Regards, Sai Kishore
6
1815
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 <iostream>
0
9714
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9594
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10599
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10346
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10347
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10090
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9173
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6863
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5531
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...

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.