Re: Calling Class Constructor from Another Constructor
ashwin <ashwindows@gmail.com> writes:
I was trying the following on VC++ 6.0
#include <iostream>
struct A
{
A(int a)
{
x = a;
}
A(int a, double b)
{
A::A(a);
y = b;
}
int x;
double y;
};
int main()
{
A a(1,2.4);
std::cout<<"x="<<a.x<<std::endl;
return 0;
}
//Output
x=-858993460
What is wrong with the program ?
It has undefined behavior, because a.x hasn't been initialized before
being read.
Calling a Constructor from Another Constructor invalid in C++ ?
No. But the result isn't what you seem to expect.
The statement
A::A(a);
in the second constructor of class A first constructs a temporary
object and intializes that object's member x with the value of a; the
temporary object is then destructed again. And the x data member of
the object under construction remains uninitialized.
What you are looking for is the possibility for a constructor to
delegate to another. In current C++, this is not possible; it
will be in a future version. Cf.
http://en.wikipedia.org/wiki/C++0x#Constructor_delegation
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]