Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weird constructors behavior

#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...

like image 770
rev3r Avatar asked Dec 18 '22 16:12

rev3r


2 Answers

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.

like image 104
Some programmer dude Avatar answered Dec 24 '22 02:12

Some programmer dude


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);
like image 42
Mattia F. Avatar answered Dec 24 '22 02:12

Mattia F.