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