Named constructors
This is one application for public static methods. The idea is that since the static method is a member of the class it means that it has access to the private members of an instance of the class, so such a method can create an object, perform some additional initialization, and then return the object to the caller. This is a factory method. The point class used so far has been constructed using Cartesian points, but we could also create a point based on polar co-ordinates, where the (x, y) Cartesian co-ordinates can be calculated as:
x = r * cos(theta)
y = r * sin(theta)
Here r is the length of the vector to the point and theta is the angle of this vector counter-clockwise to the x axis. The point class already has a constructor that takes two double values, so we cannot use this to pass polar co-ordinates; instead, we can use a static method as a named constructor:
class point
{
double x; double y;
public:
point(double x, double y) : x(x), y(y){}
static point polar(double r, double th)
{
return point(r * cos(th), r * sin(th));
}
};
The method can be called like this:
const double pi = 3.141529;
const double root2 = sqrt(2);
point p11 = point::polar(root2, pi/4);
The object p11 is the point with the Cartesian co-ordinates of (1,1). In this example the polar method calls a public constructor, but it has access to private members, so the same method could be written (less efficiently) as:
point point::polar(double r, double th)
{
point pt;
pt.x = r * cos(th);
pt.y = r * sin(th);
return pt;
}