Reputation: 17223
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
Upvotes: 0
Views: 85
Reputation: 16070
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.
Upvotes: 3
Reputation: 36
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.
Upvotes: 0