#include <iostream>
using namespace std;
class Foo
{
public:
Foo()
{
cout << 0;
}
Foo(Foo &f)
{
cout << 1;
}
};
void someFunction(Foo f) {};
int main()
{
Foo f1; //displays 0 (as expected)
Foo f2(f1); //displays 1 (as expected)
someFunction(f1); //displays 1 (why?)
someFunction(f2); //displays 1 (why?)
return 0;
}
I don't understand why function 'someFunction' calls second constructor. I thought it will just call first constructor, with no parameters, and displays 0.
Maybe I am missing something obvious...
The second constructor is a copy constructor, and when you pass an argument to a function by value it is copied, which invokes the copy constructor.
The first constructor (the default constructor) is only called when creating an object from scratch, and without any arguments.
Because when you call someFunction, the compiler invokes the copy-constructor to copy the object f1
or f2
into f
.
To avoid that, just declare the function with a reference parameter to a Foo object, like so:
int someFunction(Foo &f) {}
Then call it as usual:
someFunction(f1);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With