Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I have to put this function static

Tags:

c++

static

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...

like image 814
statquant Avatar asked Aug 13 '26 03:08

statquant


1 Answers

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.

like image 113
David Brown Avatar answered Aug 14 '26 20:08

David Brown



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!