Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c++11

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!

like image 882
YS_Jin Avatar asked Aug 08 '20 21:08

YS_Jin


People also ask

Can we call member functions without an object?

Because a member function is meaningless without an object to invoke it on, you can't do this directly (if The X Window System was rewritten in C++, it would probably pass references to objects around, not just pointers to functions; naturally the objects would embody the required function and probably a whole lot more ...

How do you call a function without an object?

Only static class functions can be called without an object using the Class::function() syntax. So, you should add static as a keyword to the definition of your functions inside the Cat class.

Which function is called without object of class?

Static methods are the methods in Java that can be called without creating an object of class.

How do you call a function without an object in C++?

You could declare the function outside the vector class but in the same namespace/file and then define it accordingly. And then in the cpp: namespace math { Vector::Vector() { ... } double scalar(const Vector& v1, const Vector& v2) { ... } }


1 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
    }
    
like image 184
cdhowie Avatar answered Nov 14 '22 23:11

cdhowie