Friday, May 11, 2012

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;
public:
foo()
{
x=20;
}
foo(int d)
{
x=d;
foo();//value should be changed to 20, but it wont
}
void show()
{
foo a;
a.show();// will print 20
foo b(10);
b.show();// will print 10. I was expecting it to print 20
return 0;
}
(This one is from my old blog.)

No comments:

Post a Comment