Using custom constructor, a struct can be initialized using own type.
struct Foo {
int x, y;
Foo(int X, int Y) : x(X), y(Y) {}
Foo(const Foo& f) : Foo(f.x, f.y) {}
};
Foo foo1(1, 2);
Foo foo2 = Foo(foo1);
However, I found that declaring the constructor wasn't necessary.
struct Foo {
int x, y;
Foo(int X, int Y) : x(X), y(Y) {}
// Foo(const Foo& f) : Foo(f.x, f.y) {} <-- This can be omitted.
};
Foo foo1(1, 2);
Foo foo2 = Foo(foo1);
I wonder how is this possible.
From https://en.cppreference.com/w/cpp/language/copy_constructor:
If no user-defined copy constructors are provided for a class type, the compiler will always declare a copy constructor as a non-explicit inline public member of its class. This implicitly-declared copy constructor has the form
T::T(const T&)
...