Connecting Tech Pros Worldwide Help | Site Map

Copy Constructor -Query

  #1  
Old July 22nd, 2005, 11:20 AM
Vivek Shah
Guest
 
Posts: n/a
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
  #2  
Old July 22nd, 2005, 11:20 AM
Victor Bazarov
Guest
 
Posts: n/a

re: Copy Constructor -Query


"Vivek Shah" <shahv@ececs.uc.edu> wrote...[color=blue]
> 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 ?[/color]

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


Closed Thread


Similar Threads
Thread Thread Starter Forum Replies Last Post
copy constructor Rahul answers 4 November 26th, 2007 03:55 AM
Operator overloading and copy constructor. Can't find the error. clicwar answers 22 July 25th, 2007 03:15 AM
probelm on copy constructor of a derived class. shuisheng answers 8 September 26th, 2006 05:45 PM
Copy constructor in C# Jesper answers 8 November 15th, 2005 08:11 AM
C++: Default Copy Constructor A answers 15 July 22nd, 2005 04:36 AM