0

Why isn't the argument passed by value ?

When I tried it, my compiler just gave me a message saying "you probably meant Foo(const Foo&) ."

What is the reason for this ?

Tasdik Rahman
  • 2,160
  • 1
  • 25
  • 37
  • 1
    Actually because if you pass by value compiler have to make a copy of ypuir varibale, so call copy constructor. In result you'll have to make a copy to make a copy, but you need to make a copy to make a copy and so on. – Lol4t0 Sep 14 '14 at 13:26
  • We have a similar SO question here http://stackoverflow.com/questions/13413419/parametized-constructor-not-an-copy-one – Athiruban Sep 14 '14 at 13:27
  • 3
    @40two Mainly to avoid infinite recursion – juanchopanza Sep 14 '14 at 13:30

2 Answers2

7

Because pass by value requires a copy constructor in the first place.

So to avoid infinite recursion, the pass by reference copy constructor has to be defined before the pass by value version if we really want to have a pass by value one. As it does not make much sense to have a pass by value copy constructor, the standard forbids it.

WiSaGaN
  • 46,887
  • 10
  • 54
  • 88
  • so.. wouldn't that require a value(again) ? – Tasdik Rahman Sep 14 '14 at 13:26
  • @prodicus Indeed. So to avoid this, one needs to define other version first. – WiSaGaN Sep 14 '14 at 13:30
  • You can't have a "pass by value version" at all. – T.C. Sep 14 '14 at 13:33
  • @T.C. That's true, and it wouldn't make much sense to have one either. But OP asks for the reason, so here it is. – WiSaGaN Sep 14 '14 at 13:36
  • Well, this explanation makes sense at the lowest technical level. But the C++ language is flush with automatic rewrites of code. Formal arguments of function type are adjusted to pointers, formal arguments of array type are adjusted to pointers, actual arguments to variadic functions are promoted, and possibly more. So it's also necessary to address this aspect, why there isn't an automatic rewrite. Possible reasons include that it would not save much typing, that it would complicate the language and increase the size of the standard, and also that nobody's expressed any interest... :) – Cheers and hth. - Alf Sep 14 '14 at 13:42
5

You are simply not allowed to pass it by value - §12.8 [class.copy]/p6 of the standard explicitly prohibits it :

A declaration of a constructor for a class X is ill-formed if its first parameter is of type (optionally cv-qualified) X and either there are no other parameters or else all other parameters have default arguments. A member function template is never instantiated to produce such a constructor signature.

The reason for this prohibition, as explained in the comments, is infinite recursion - "to make a copy, you have to make a copy" doesn't make much sense.

T.C.
  • 133,968
  • 17
  • 288
  • 421