I am trying t understand the Named Constructor Idiom in the example I have
Point.h
class Point
{
public:
static Point rectangular(float x, float y);
private:
Point(float x, float y);
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);}
main.cpp
#include <iostream>
#include "include\Point.h"
using namespace std;
int main()
{
Point p1 = Point::rectangular(2,3.1);
return 0;
}
It does not compile If Point::rectangular is not static and I don't understand why...
In this context, the static keyword in front of a function means that this function does not belong to any particular instance of the class. Normal class methods have an implicit this parameter that allow you to access the members of that specific object. However static member functions do not have the implicit this parameter. Essentially, a static functions is the same as a free function, except it has access to the protected and private members of the class it is declared in.
This means you can call static functions without an instance of that class. Instead of needing something like
Point p1;
p1.foo();
You simply do this:
Point::foo();
If you tried to call a non static function like this, the compiler will complain, because non-static functions need some value to assign to the implicit this parameter, and Point::foo() doesn't supply such a value.
Now the reason you want rectangular(int, int) to be static is because it is used for constructing a new Point object from scratch. You do not not need an existing Point object to construct the new point so it makes sense to declare the function static.
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