Why in some cases can I call a member function without an object?

Viewed 149

I am working with a numerical library deal.ii, within which a lot of numerical tools are integrated. What I found weird is that I can call member functions directly without defining an object. For example, I can directly call

Vectortools::interpolate_boundary_condition();

Could you tell me when I can directly call the member functions without defining an object? Thank you!

2 Answers

There's two cases you can do this:

  1. The member function is declared static -- in that case it is basically a free function but scoped to the class. Notably, this cannot be used in a static function since an object is not required to invoke it.

  2. When you are within a member function whose this pointer is implicitly convertible to a pointer to the type being invoked on (Vectortools in this case). Note that this is invoked on an object (implicitly *this). This can be used to invoke an inherited member that is being overridden or hidden:

    class A {
    public:
      virtual void foo();
    };
    
    class B : public A {
    public:
      virtual void foo() override;
    };
    
    void B::foo() {
      // Do something
    
      // Invoke the method we've overidden from A.
      A::foo();
    
      // Then do something else
    }
    

This is because the function you are calling is a static function. A static function is a function which can be called without make an object of the class. You can only access static data members of class using static functions.

Related