static
Methods¶
Methods without Object¶
What we know now:
Methods are great
Name and variable ⟶ Method (like
p.move(1,2)
)⟶ clear writing
Methods are invoked on objects (mostly)
But: global functions? Methods without an object?
Not bound to objects
Same scheme (“method of the class”)?
Example: add two point objects (⟶ vector addition)
Creates a third point object
Leaves the two addends unmodified
Object method?
Addition is not normally invoked on an addend
But it belongs to
class point
somehow
Naive Implementation: Global Function¶
In C, one would define such a thing straightforwardly, as a global function
In C, there are no functions other than global
#include <gtest/gtest.h>
class point
{
public:
point(int x, int y) : _x{x}, _y{y} {}
int x() const { return _x; }
int y() const { return _y; }
private:
int _x;
int _y;
};
point add_points(point lhs, point rhs)
{
int x = lhs.x() + rhs.x();
int y = lhs.y() + rhs.y();
return point{x, y};
}
TEST(static_suite, global_function)
{
point p1{1,2};
point p2{3,4};
point sum = add_points(p1, p2);
ASSERT_EQ(sum.x(), 4);
ASSERT_EQ(sum.y(), 6);
}
C++: static
Method¶
C++ adds another meaning for the
static
keywordGlobal function, but …
Not bound to an object (not called like
p.add(...)
But inside class scope (called like
point::add(p1, p2)
)
#include <gtest/gtest.h>
class point
{
public:
point(int x, int y) : _x{x}, _y{y} {}
int x() const { return _x; }
int y() const { return _y; }
static point add(point lhs, point rhs)
{
int x = lhs.x() + rhs.x();
int y = lhs.y() + rhs.y();
return point{x, y};
}
private:
int _x;
int _y;
};
TEST(static_suite, static_method)
{
point p1{1,2};
point p2{3,4};
point sum = point::add(p1, p2); // <--- note the scope!
ASSERT_EQ(sum.x(), 4);
ASSERT_EQ(sum.y(), 6);
}