+ 1

Direct vs copy initialization

Hi, I am learning about the types of initialization, and so far I've understood the topic well. However I have a problem when trying to make a class that uses copy init. Specifically this case: class SomeCl { int x; public: explicit SomeCl (int a) {/* k1 should be initialized with this constructor */ x = a; cout << "This is direct init."; } SomeCl (const Somecl &a) { //k2 with this x = a.x; cout << "This is copy init."; } }; int main() { SomeCl k(5); // this works with the first SomeCl k2 = 5; return 0; } And it reports an error that says "conversion from int to non-scalar type:

25th May 2019, 10:31 PM
M vC
M vC - avatar
4 Respostas
+ 4
Well by writing explicit in front of SomeCl(int a), you're telling the compiler that it must not do automatically the conversion from int to SomeCl; Then by typing SomeCl k2 = 2; you ask the compiler exactly what you told him not do.
26th May 2019, 4:39 AM
Paul
+ 1
Copy init would be: SomeCl k(5); SomeCl k2(k); What you are doing is using the '=' operator with integers, which you would need to overload to use: SomeCl& operator=(const int& other) { this->x = other; return *this; }
26th May 2019, 3:15 AM
Zeke Williams
Zeke Williams - avatar
0
Thank you for your answers, especially Zeke, however the compiler still says "conversion from int to non-scalar type 'SomeCl' requested. The only problem I have understanding is with this specific case, where I am trying to use copy init. with integers. I've played with other ways and types of init. and they all make sense, however this is the one that is making trouble.
26th May 2019, 6:49 AM
M vC
M vC - avatar
0
Oh, and for your answer ~swim~ , I am just trying to see if the program makes a difference between copy and direct init. and this is why I made those cout << "this is..." If I remove explicit or explicitly wrote SomeCl(5), the othwr constructor wouldn't "run", but only the first which says direct init.
26th May 2019, 6:53 AM
M vC
M vC - avatar