Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > C++ > why copy constructor is not being called?

Reply
Thread Tools

why copy constructor is not being called?

 
 
suresh
Guest
Posts: n/a
 
      04-15-2008
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>
using namespace std;
class base
{
char s;
public:
base( ){cout<< "construction" << endl;}
base(const char a ) {cout << "construction with arg" << endl;}
base(const base & a){cout <<"copy constructor" << endl;}
base & operator=(const base & a){cout << "assignment operator" <<
endl;}
~base( ) {cout << "destruction" << endl;}
};

main ( )
{
base b1 = 'x'; //why copy constructor is NOT called here as given in
books?
base b2 = b1; //copy constructor is called

}
 
Reply With Quote
 
 
 
 
Rolf Magnus
Guest
Posts: n/a
 
      04-15-2008
Pete Becker wrote:

> the compiler should construct a temporary object of type base from the
> argument 'x', then copy that temporary into b1. However, the answer to
> the original question is that the compiler is permitted to elide the
> copy if the copy constructor has no side effects,


Actually, the compiler is also allowed to do this if the constructor does
have side effects. Printing to cout is a side effect.

 
Reply With Quote
 
 
 
 
Andrey Tarasevich
Guest
Posts: n/a
 
      04-15-2008
suresh wrote:
> ...
> 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
> ...


Because the language specification explicitly allows the compiler to
optimize away the copying of temporary objects, even if the
copy-constructor has any side-effects.

In other words, the constructor might get called. Or it might not get
called. It might depend on the compiler, on the compiler settings and
even on the concrete context in the code. Just don't rely on it.

--
Best regards,
Andrey Tarasevich
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
template copy constructor vs normal copy constructor cinsk C++ 35 10-10-2010 11:14 PM
A constructor calling another constructor (default constructor)? Generic Usenet Account C++ 10 11-28-2007 04:12 AM
findcontrol("PlaceHolderPrice") why why why why why why why why why why why Mr. SweatyFinger ASP .Net 2 12-02-2006 03:46 PM
templatized copy constructor not being deduced lhr_cool_guy@yahoo.com C++ 3 12-29-2005 08:58 AM
Copy constructor: why can't I copy objects as if they were structs? rdc02271 C++ 24 12-27-2005 12:38 PM



Advertisments