@@ -26,7 +26,7 @@ struct Foo
2626 }
2727
2828 // explicit Foo(int)
29- Foo (int )
29+ explicit Foo (int )
3030 {
3131 cout << " Constructor called with int / copy init\n " ;
3232 }
@@ -42,22 +42,24 @@ void initialize_variable()
4242 cout << " \n --- Variable Initialization Examples ---\n " ;
4343 // There are there common ways to intialize a variable
4444 // * Default
45- int initDefaultVar;
46- Foo initDefaultObj;
45+ [[maybe_unused]] int initDefaultVar;
46+ [[maybe_unused]] Foo initDefaultObj;
4747
48- // *Traditional
49- // * copy-init: Type var = value;
50- // 1. Compiler tries to create a temporary Foo from 2.3 by implicit conversion (calls Foo(<implicit int to double>) ).
51- // 2. If constructor is explicit, implicit conversion is not allowed → error.
52- // 3. Otherwise, temporary Foo is created and then copy/move into copyInitObj2.
53- Foo copyInitObj = 2.3 ; // implicit 2.3(float) -> 2(int) -> call Foo(int) -> create a temporary Foo -> is copied or moved into copyInitObj
48+ // * Traditional initialization
49+ // * Copy-init: Type var = value;
50+ // 1. Compiler tries to convert the value to a temporary Foo.
51+ // 2. If the constructor is explicit, implicit conversion is blocked -> compilation error.
52+ // 3. Otherwise, a temporary Foo is created and then copied/moved into the variable.
53+ [[maybe_unused]] Foo copyInitObj = (Foo)2.3 ; // explicit cast: double 2.3 -> int 2 (implicit narrowing) -> Foo(int) -> temporary Foo -> copied/moved into copyInitObj
54+ // Foo copyInitObjError = 2.3; // ERROR: implicit conversion blocked by explicit constructor
55+ // We can explicitly prevent certain conversions using = delete or using {}
5456
5557 // * direct-init: Type var(value);
56- Foo directInitObj (4 ); // call Foo(int)
57- Foo directInitObj2 (4.3 ); // look for constructor -> implicit 4.3(float) -> 4(int) -> call Foo(int) ->
58+ [[maybe_unused]] Foo directInitObj (4 ); // call Foo(int)
59+ [[maybe_unused]] Foo directInitObj2 (4.3 ); // look for constructor -> implicit 4.3(float) -> 4(int) -> call Foo(int) ->
5860
5961 // * Brace init
6062 // calls the constructor directly without allowing implicit conversions.
61- Foo braceInit{3 };
63+ [[maybe_unused]] Foo braceInit{3 };
6264 // Foo braceInit2{3.3}; // ERORR => Prefer this way
6365}
0 commit comments