Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a class member function recursively from its own defintion in C++?

I'm new to C++ and I need a class member function to call itself from its own definition, like this -

class MyClass {
public:  // or private: ?
    // Some code here
    // ...

    void myfunction();

    // ...
};

void MyClass::myfunction()
{
    // Some code here
    // ...

    // Call MyClass::myfunction() here, but how?    

    // ...
}

but I don't know the proper syntax for it and how can it be called by itself without creating an object usually done like this - object_name.member_function(), if possible?

And, will there be any difference if myfunction() belongs to public: or private:?

like image 296
PalashV Avatar asked Dec 05 '22 03:12

PalashV


1 Answers

Since the function isn't static, you already do have an instance to operate on

void MyClass::myfunction()
{
    // Some code here
    // ...

    this->myfunction();

    // ...
}

You could leave the this-> off, I was just being more clear about how the function is able to be called.

like image 178
Cory Kramer Avatar answered Dec 06 '22 15:12

Cory Kramer