Copy vs Direct vs Uniform initialization | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Copy vs Direct vs Uniform initialization

I searched for it on the internet, got a stack overflow answer, but could not answer me exactly. For constructors, classes, explicit constructors, it's okay. But why prefer int a(7); over int a = 7; I don't see any explicit constructors or anything like that. Why should we prefer uniform over direct over copy initialization in this case? As this site says "Favor direct initialization over copy initialization". https://www.learncpp.com/cpp-tutorial/2-1-fundamental-variable-definition-initialization-and-assignment/ Thanks

6th Sep 2018, 2:46 AM
Deepesh Choudhary
Deepesh Choudhary - avatar
1 Answer
+ 1
It's probably preferable in constructor initializer list with a custom type for the sake of performance by constructing it directly inside the data member, for example class Foo { public: Foo(int a) : b(a), c(a) { } Foo(int, int, int); private: int b, c; }; class A { public: A(Foo arg) : x(arg) { } // instead of A(Foo arg) { x = arg } private: Foo x; } or instantiating an object with multiple parameters as Foo f1(2, 4, 8); For having type checking while compilation, using list-initializer is preferable. For example passing double types as arguments causes the compiler issue some diagnostic messages (either warning or error) Foo f2{2.4, 5, 1.3}; Other than that, using it in a normal way to initialize variables, reduces the program's readability because of its confusing look with a function call.
6th Sep 2018, 7:03 AM
Babak
Babak - avatar