I'm fairly new to C++ and VC++, but for the most part it seems to do most of
the same things that can be done in Java, with just some syntactic and
structural adjustments. However, one thing I haven't been able to figure out
is how to call one constructor from another within a class. It's easy enough
to call the base class's constructor from the derived class, but that's not
what I'm trying to do.
For example, in Java (or J#) it's easy to do this:
public class Circle
{
private int PointX;
private int PointY;
private int Radius;
public Circle()
{
this.PointX = 0;
this.PointY = 0;
this.Radius = 0;
}
public Circle(int x, int y)
{
this();
this.PointX = x;
this.PointY = y;
}
public Circle(int x, int y, int r)
{
this(x, y);
this.Radius = r;
}
}
However, trying to do the same thing in VC++ doesn't work:
// Sphere.h (partial file)
class Sphere
{
public:
Sphere(void);
Sphere(int x, int y);
Sphere(int x, int y, int r);
~Sphere(void);
private:
int PointX;
int PointY;
int Radius;
};
// Circle.cpp (partial file)
#include ".\circle.h "
Circle::Circle( void)
{
this->PointX = 0;
this->PointY = 0;
this->Radius = 0;
}
Circle::Circle( int x, int y)
{
Circle();
this->PointX = x;
this->PointY = y;
}
Circle::Circle( int x, int y, int r)
{
Circle(x, y);
this->Radius = r;
}
In the C++ version, I also tried using this() instead of Circle(), which
caused a compiler error. I also tried doing it without the this-> specifier,
which made no difference. The end result if you call the second constructor
is that the X and Y values have been set, and the Radius is uninitialized.
If you use the third constructor, you get exactly the opposite results. (And
I don't mean they have values of zero; looking at them with the debugger, I
see values of -842150451 for the uninitialized members.)
So is there any way in C++ to let one constructor build on another like
this?
Thanks for any help.