Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > C++ > Copy Constructor -Query

Reply
Thread Tools

Copy Constructor -Query

 
 
Vivek Shah
Guest
Posts: n/a
 
      04-29-2004
Hi,
Given below is apiece of code which I was writing to clear my concepts
of copy constructor. I have a function f() which takes Class A object
through call by value and return the same object. Copy constructor is
called when we pass the argument by value and we return from the
function and also we initialize.

In the main function, I check the number of time the copy constructor
is called, I expect it to be 3
(1) parameter passing in f(a)
(2)return in f(a)
(3) initialization of c = f(a)

But it seems the copy constructor is called twice ..Why is that ?

static int num;
A::A(const A& A1)
{
cout<<" Inside COPY Constructor " <<++num <<endl;
}


const A f(const A z)
{
cout << "Inside Function" <<endl;
return(z);
}


int main()
{
A a(5);
A c = f(a); // c is initialized by return value of function f()
cout << num; // Shouldnt num be 3 ...it is giving 2
}

Regards
-Vivek Shah
 
Reply With Quote
 
 
 
 
Victor Bazarov
Guest
Posts: n/a
 
      04-29-2004
"Vivek Shah" <(E-Mail Removed)> wrote...
> Hi,
> Given below is apiece of code which I was writing to clear my concepts
> of copy constructor. I have a function f() which takes Class A object
> through call by value and return the same object. Copy constructor is
> called when we pass the argument by value and we return from the
> function and also we initialize.
>
> In the main function, I check the number of time the copy constructor
> is called, I expect it to be 3
> (1) parameter passing in f(a)
> (2)return in f(a)
> (3) initialization of c = f(a)
>
> But it seems the copy constructor is called twice ..Why is that ?


Read about "return value optimisation" or "RVO". The compiler is
allowed to optimise the creation of a temporary away and return the
object directly in your 'c'.

Victor


 
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
Calling base class constructor from derived class Copy constructor ali C++ 4 03-05-2007 09:15 AM
deep/shallow copy - constructor v Object.copy() VisionSet Java 8 04-29-2004 10:41 PM
Copy constructor hides default constructor Aire C++ 3 01-25-2004 05:47 PM



Advertisments