C++ Syntax: Static Member Functions
MORE C++ syntax, please!!!
Take a look back at our insertHelper() helper function:
// our insert helper function
void IntTree::insertHelper(Node*& tree, int k) {
if (tree == nullptr) {
tree = new Node{k}; // Assumes a constructor for Node
}
else if (k < tree->key_) {
insertHelper(tree->left_, k);
}
else {
insertHelper(tree->right_, k);
}
}
There's something quite interesting about this code…
Normal member functions pass along the this object so that we can access member variables, but this helper function is recursing down through our nodes, and doesn't care at all about the IntTree instance that the subtree belongs to.
If we have a member function that doesn't need a this object, it can be declared static in the class definition. For example,
class IntTree {
public:
void insert(int k);
...
private:
struct Node {
...
};
Node* root_;
static void insertHelper(Node*& tree, int k);
};
Note that we only put static when declaring the member function in the class definition. In the implementation, it already knows and we don't need to say static again.
I remember hearing about “class methods” for Python. Is a “static member function” the same kind of thing?
Yes. If you know that term, it might help to know it's the same idea. But if you haven't heard of it, no worries.
Using a Static Member Function
From outside the class, there's a big difference between how we call a regular member function and how we call a static one. If we have an object myObject that is an instance of class MyClass, we would write
myObject.myMemberFn(foo, bar); // Call regular member function
MyClass::myStaticMemberFn(xyzzy); // Call static member function
but for code inside a member function for the class, the calls look the same:
myMemberFn(foo, bar); // implicitly this->myMemberFn(foo, bar)
myStaticMemberFn(xyzzy); // implicitly MyClass::myStaticMemberFn(xyzzy);
So our code wouldn't change at all. We just add the word static in the class definition and it's all good.
Would it hurt if I forgot to put
staticin there?
For our helper functions, no. It would pass a redundant
thisobject along for the ride, but that wouldn't cause any problems.
But adding
staticwhen we don't plan to use any data members can help catch bugs. For example, if I accidentally saidroot_->key, it would be an error.
And catching errors at compile time is a good thing.
(When logged in, completion status appears here.)