I have seen code like this, so I'm trying to find the reason.
What's the main reason for having static functions that act as constructors, instead of having actual constructors?
I mean something like:
class MyClass
{
public:
static MyClass CreateFrom( bar );
static MyClass CreateFrom( foo );
...
}
instead of:
class MyClass
{
public:
MyClass( bar );
MyClass( foo );
...
}
This is called the "named constructor idiom".
It's typically used when:
1, 1.0, 1
is supposed to mean something different from 1, 1, 1.0
).double
.In this case a single angle(double dist)
can't distinguish between input in kilometer vs. miles, but: angle_from_miles
and angle_from_kilomters
can do that quite easily.
They are called Named Constructors
.
The are basically used when you want to construct an object which requires to pass a particular set of parameters but internally you need to construct the object differently.
For example you have a class like:
class AREA
{
double area;
AREA(int x);
};
//how will you construct the object differently in case of circle and square??
For this purpose, we have named constructors which help to create a relevant object.
So we may create 2 static methods inside the class as:
static AREA square(int x)
{ return AREA(x*x); }
and
static AREA circle(int x)
{ return AREA(x*x*3.14); } //or a more accurate PI value
Thus, we may call the relevant static function to return the object initialized with the required area.
NOTE: These are static as while creating an object for a particular class you shouldn't be requiring an object to do so.
Check THIS for more details.
The most obvious benefits are:
Another reason is that it is easier in some cases to initialize the class within a function body, rather than using an initialization list.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With