CS 70

C++ Syntax: Static Member Functions

  • Pig speaking

    MORE C++ syntax, please!!!

Take a look back at our insert 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 is something quite interesting about this code…

Does this helper function directly use any data members of our IntTree class?

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.

  • Duck speaking

    I remember hearing about “class methods” for Python. Is a “static member function” the same thing?

  • LHS Cow speaking

    Yes. If you know that term, it might help to know it's the same idea. But if you've not 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 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 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.

  • Hedgehog speaking

    Would it hurt if I forgot to put static in there?

  • LHS Cow speaking

    For our helper functions, no. It would be passing a redundant this object along for the ride, but that wouldn't cause any problems.

  • RHS Cow speaking

    But adding static when we don't plan to use any data members can help catch bugs. For example, if I accidentally said root_->key, it would be an error.

  • LHS Cow speaking

    And catching errors at compile-time is a good thing.

(When logged in, completion status appears here.)