+ 4

Why is the 1st constructor being called, when I provoke the second one?

I have the following class: class Data { int* dat; int csize; Data(bool z=0 ,int cs=0) { cout<<"Default"<<endl; dat = new int[100]; for(int i=0;i<cs;i++) dat[i]=0; dat[0]=(z?0:1); } Data(string a) { cout<<"Special"<<endl; csize = a.length(); dat =new int[a.length()]; for(int i=0;i<a.length();i++) dat[i] = a.at(a.length()-i-1)-48; } friend ostream& operator<<(ostream&,Data); }; Now, on calling the following in main: Data d("23334"); cout<<d<<endl; The program prints 0. Why?

20th Jul 2017, 3:12 PM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar
7 ответов
+ 3
The ostream operator works fine with the 1st constructor... Also, I copy the size into a variable calles csize, in both constructors...
20th Jul 2017, 3:13 PM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar
+ 3
@Immortal I had to erase it here, Thanks to SoloLearn's 512 char limit...
20th Jul 2017, 3:39 PM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar
+ 3
The complete class: class Data { int* dat; int csize; Data(bool z=0 ,int cs=0) { cout<<"Default"<<endl; csize = cs; dat = new int[100]; for(int i=0;i<cs;i++) dat[i]=0; dat[0]=(z?0:1); } Data(string a) { cout<<"Special"<<endl; csize = a.length(); dat =new int[a.length()]; for(int i=0;i<a.length();i++) dat[i] = a.at(a.length()-i-1)-48; } friend ostream& operator<<(ostream& os,Data d) { for(int i=csize-1;i>=0;i--) os<<d.dat[i]; return os; } };
20th Jul 2017, 3:41 PM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar
+ 3
@Immortal Yes, and this works, maybe as int can never hold a string, but bool may...
20th Jul 2017, 4:13 PM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar
+ 2
I interchanged the bool and the int parameters, and it started working... So, can i conclude that bool can even analyze strings as true or false? Thank You for answering!
20th Jul 2017, 3:38 PM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar