Why the named constructors are static

I read a post about Named Constructors . He declared that named constructors are static. What could be the reason for this. Wouldn't a static method serve the same purpose?

+6
source share
4 answers

A non-static function is associated with a class object.

In this case, the whole point of the function is to create a class object. When you call a function, there is no class instance with which this function call can be associated.

+14
source

They must 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 the Named Constructor Hierarchy, you must create private or protected constructors, so you cannot have a constructed object in direct form.

On the other hand, static methods should not have objects to call, so they also do not need constructors.

Therefore, you can use static methods to do something like returning a constructed object.

+3
source

It is not part of some kind of “magic syntax”. Its just a static member that works like a factory for the Point class. I will copy the example from this link and add explanatory 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 the Point class

+1
source

Well, in a way, it actually can. Named constructors are effectively the result of combining a factory into a target type. In the original factory template, you will 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 you want to create a point and do not require a complex factory type, you can simply move the factory functionality to the point type itself. Then you will need to make the member function "Named Constructor" static for the reasons mentioned in the other answers.

0
source

Source: https://habr.com/ru/post/949914/


All Articles