1 Replies - 463 Views - Last Post: 04 February 2011 - 05:02 AM Rate Topic: -----

#1 Guest_stankefa*


Small code which i don't understand

Posted 04 February 2011 - 03:32 AM

#include <iostream>
using namespace std;
class X {
   X () : myID(id) {}
   X (const X& right) : myID(++id) {}
   friend ostream& operator<< (ostream&, const X&);
   static int id;
   int myID;

int X::id = 0;

ostream& operator<< (ostream& os, const X& x) {
   return os<<x.myID;

X f (X x1, X& x2) {
   x1 = x2;
   return x2;
void main () {
   X x1, x2 = x1;
   X x3 = f(x1,x2);

What I don't understand is how the 25. line of the program works (3rd line of main() function). I know that it should use a copy constructor, and it does it at first,but after finishing copy constructor function it calls the f function and after that initializes x3 with the returned value of function f. Why does it call function f at all after copy constructor? Isn't it supposed to call only copy constructor?
What i'm trying to say is that I don't understand how copy constructor works when I have a function on the right side... Please help.

Is This A Good Question/Topic? 0

Replies To: Small code which i don't understand

#2 oscode   User is offline

  • D.I.C Regular

Reputation: 109
  • View blog
  • Posts: 257
  • Joined: 24-October 10

Re: Small code which i don't understand

Posted 04 February 2011 - 05:02 AM

Here is what happens step by step, assuming no compiler opimizations:
x1 is constructed
x2 is copy constructed
f1 is called
x1 is copy constructed into a local x1 (pass by value)
x1 is assigned x2
f2 returns - x2 is copy constructed to x3

This post has been edited by oscode: 04 February 2011 - 05:03 AM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1