Calling constructor from constructor

I was trying a few whiteboard programs, just for fun. In one of them I called a constructor from within another constructor. Code compiled without any fuss,but code didn’t worked the way I was expecting.  I found out that when calling a constructor from within a constructor a temporary unnamed constructor is created. That is the reason why program is not behaving the way I was expecting. Check out this…

using namespace std;

class foo
int x;

foo(int d)
foo();//value should be changed to 20, but it wont
void show()
foo a;;// will print 20
foo b(10);;// will print 10. I was expecting it to print 20
return 0;

(This one is from my old blog.)

Leave a Reply

Your email address will not be published. Required fields are marked *