why copy constructor is not being called?

S

suresh

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

}
 
R

Rolf Magnus

Pete said:
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.
 
A

Andrey Tarasevich

suresh said:
...
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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,962
Messages
2,570,134
Members
46,692
Latest member
JenniferTi

Latest Threads

Top