Reputation: 9380
I was reading a post about Named Constructors. It has declared the named constructors static. What can be the reason for that. Wouldn't a non static method serve the same purpose?
Upvotes: 7
Views: 801
Reputation: 34626
Well, in a sense it actually can. Named Constructors are effectively the result of merging a factory into the target type. In the original factory pattern, you would have something like this:
class PointFactory {
public:
Point rectangular(float x, float y); // Rectangular coord's
Point polar(float radius, float angle); // Polar coordinates
// Of course these *could* be static, but they don't *have* to be.
private:
/* ... */
};
If all you want is to create a Point and don't really require a complicated factory type, you can simply move the factory's functionality to the Point type itself. Then you would have to make the then "Named Constructor" member function static
for the reasons stated in the other answers.
Upvotes: 1
Reputation: 7357
Its not a part of some "magic syntax". Its just a static member that works as factory for class Point. I'll copy example from this link and add explaining comments:
#include <cmath> // To get std::sin() and std::cos()
class Point {
public:
static Point rectangular(float x, float y); // Its a static function that returns Point object
static Point polar(float radius, float angle); // Its a static function that returns Point object
// These static methods are the so-called "named constructors"
...
private:
Point(float x, float y); // Rectangular coordinates
float x_, y_;
};
inline Point::Point(float x, float y)
: x_(x), y_(y) { }
inline Point Point::rectangular(float x, float y)
{ return Point(x, y); } //Create new Point object and return it by value
inline Point Point::polar(float radius, float angle)
{ return Point(radius*std::cos(angle), radius*std::sin(angle)); } //Create new Point object and return it by value
So, Point::rectangular
and Point::polar
is just a factory for class Point
Upvotes: 1
Reputation: 56479
They have to be static
methods.
class Point {
public:
static Point rectangular(float x, float y); // Rectangular coord's
static Point polar(float radius, float angle); // Polar coordinates
...
private:
Point();
Point(float x, float y); // Rectangular coordinates
float x_, y_;
};
In Named Constructor Idiom you should make constructors private
or protected
, so you cannot have an constructed object in a straight way.
On the other hand, static
methods don't need to have objects to call, so they don't need constructors too.
Therefore, you can use static
methods to do something such as returning a constructed object.
Upvotes: 3
Reputation: 490148
A non-static function is associated with an object of a class.
In this case, the whole point of the function is to create an object of the class. When you call the function, there is no instance of the class with which that function call could be associated.
Upvotes: 16