0

Suppose I have an object called Myobj and this object has all the defaults (copy cstr , move cstr, assignment and cpy assignment). Now suppose there is a method as such

void fooA(foo& f){..}  --->A

and then another method as such

void fooB(foo f){..}   --->B

Now when asked why the copy constructor is not called in case of A and is called in-case of B my answer and understanding is as follows. Kindly correct me if its wrong

The reason its not called for case A is because foo& is a reference to foo and not foo therefore the copy constructor of foo is not called. The f in case A is simply an alias to the passed object.

The reason its called in case B is because foo is the object foo and not a reference to the foo.Therefore the copy constructor of foo is called. The cpy cnstr is foo::foo(const foo& f). So incase of the statement

fooB(someobject);

The equivalent would be on the function as

void fooB(foo f){..} gives  fooB f (someobject); //Cpy constr is called

Kindly let me know if my answer and understanding is correct

MistyD
  • 16,373
  • 40
  • 138
  • 240

2 Answers2

3

Yes, but IMO you are wording is quite strange or maybe you are over-complicating things a bit.

The second signature uses a "pass by value" method. As opposed to the first example, where a "pass by reference" is used. The idea is that you operate on the value of the argument, and not the argument itself.

This means a temporary copy of the passed parameter is made, with the lifetime limited by the scope of the function.

luk32
  • 15,812
  • 38
  • 62
0

Yes that is correct. I think you mean in the first case that it is a reference to f not a reference to foo. Same with in the second case it is that you're passing a copy to f not the f itself.

aditsinha
  • 36
  • 1
  • 3
  • 1
    The first case is a reference to foo. The second case is not a reference. The types are different – MistyD May 11 '14 at 19:50
  • No theyre the same types. The first is passing an argument by reference, the second is passing by value. http://stackoverflow.com/questions/373419/whats-the-difference-between-passing-by-reference-vs-passing-by-value – aditsinha May 11 '14 at 19:53
  • In both cases, the function that is called is getting a `foo` – aditsinha May 11 '14 at 19:54
  • 1
    `foo&` is not the same as `foo`. There are times when a static cast (for example) will not work if you forget a `&`. Of course in both cases there is a `foo` (same type) involved. – David K May 11 '14 at 19:57