Search code examples
c++member-functionsthis-pointer

What happens when a member function with no arguments is called by an object in c++


Suppose we have a member function of class X and it is X f() which returns an object of class X and takes no arguments.

So if it is called by an object of class X, say X obj is the object.

So if we call obj.f(), so as per the C++ rules a secret argument is passed to the function f() and that is this pointer of the object which contains the address of the object which calls f().

So my confusion is how it is managed by C++, because this means we can never have a member function in C++ with no arguments at all, because every time a secret argument would be passed.

For a function with an argument say func(int a), it is actually a function which can take 2 arguments, where one of the arguments is the secret argument (this pointer) and the other is int a.

So what can we do if we strictly want a member function in C++ with no arguments at all (like in the case of an interrupt service routine)?

Please tell me if I am wrong or if I am missing some concept.


Solution

  • What you want is a class function, aka a static member function.

    It will have no implicit this pointer.

    In C++, you can declare one with the static keyword:

    class foo
    {
    public:
        static void bar();
    };
    
    void foo::bar()
    {
        this; // error
    }