Below is sample class written with copy constructor in c++.
class Foo {
public:
Foo() { std::cout << "Foo::Foo\n";}
~Foo() { std::cout << "Foo::Foo\n";}
Foo(const Foo& rhs) {
std::cout << "cctor\n";
}
Foo& operator=(const Foo& rhs) {
if (&rhs == this) return *this;
std::cout << " operator =\n";
return *this;
}
void bar() { std::cout << "Foo::bar\n";}
};
Now we can write in couple of ways which would invoke copy constructor of the class.
Foo x;
Foo y;
Foo z = x; // This calls copy constructor
Foo a(z); // This also calls copy constructor
So out of two style which one is preferred and is there any explanation for that?. Or these two are more of style preference of developer.
out of two style which one is preferred
Foo z = x;
is copy initialization vs Foo A(z);
is direct initialization. If you understand the difference between the two, you will be able to decide which is suitable in which situation. There is no one fits all in c++. Asking which is preferred assumes that one of them is "always" preferred over the other, which is not the case in reality. Depending on the context one might be preferred over the other.
For example, direct initialization would work even when the copy constructor is explicit while copy initialization would not work there. In implicit conversions where copy initialization is performed, the explicit copy ctor won't be used.