0

I thought that when you do:

Foo f1;
Foo f2 = f1;

The line Foo f2 = f1; calls the copy constructor of Foo and that it was equivalent to:

Foo f1;
Foo f2{f1};

However this seems not to be the case:

class Foo
{public:
    Foo() {}
    explicit Foo(const Foo& other) {}
};


int main()
{


    Foo f1;
    //Foo f2 = f1; // DOESN'T WORK IF COPY CONSTRUCTOR MADE EXPLICIT
    Foo f2{ f1 }; // THIS WORKS WITH EXPLICIT
}

Why is this if there's no conversion? 'f1' is a Foo object, there shouldn't be a conversion. Why does it fail? Also in the following:

Foo funcReturningFoo()
{
    Foo f;
    return f; /* NO SUITABLE COPY CONSTRUCTOR IF MADE EXPLICIT */
}
Zebrafish
  • 11,682
  • 3
  • 43
  • 119
  • `Foo f2 = f1` is the equivalent of `Foo f2(f1)` (or `Foo f2{f1}`) IF the relevant constructor is not explicit. By tagging the copy constructor as `explicit` you've *explicitly* told the compiler that you do not want that equivalence and the compiler is duly not doing the conversion. – Peter Jan 08 '23 at 21:24

0 Answers0