MAG
MAG

Reputation: 3075

C++ static object Class function

Some code: Please see the class myClass below . it has a constructor and a public recursive function find. Please see code:

#include <iostream>
using namespace std;

class myClass{
    public:

    myClass() {
        //do stuff
    }

    int find(int i) {
        static int j = 10;

        if (i > 15)
            return i;

        j = j + 1;
        return i * find(j + 1);
    }
};

int main() 
{

    myClass mC1 ,mC2;

    cout<< " 1.... return value = "<< mC1.find(10);
    cout<< " \n 2... return value = "<< mC2.find(10);

    return 1;
}

output:

1.... return value = 5241600 
2.... return value = 170

The above progemn has a class myclass having a function find .. "find" function has a variabe . This is static which is required as i wanted a recursive function . Problem is static varible has life of a program & binded to class .

However I want the static to be object specfic and not class scope . I wanted both the function calls to return me same value .

Simply put , how to make a static varable in a class function , to be per object and not for whole class...

Upvotes: 0

Views: 613

Answers (2)

Dietmar K&#252;hl
Dietmar K&#252;hl

Reputation: 154045

If you want a per object variable you need to make it a member of the respective object. There is no way to declare a variable inside a function to be specific to objects. The way you use use static member could be changed to be non-static anyway, i.e., you would get the necessary context: Make the function non-static and store the data in the object as needed.

That said, just because a function is recursive doesn't mean that it needs any sort of static context. Normally, all the necessary context is passed to the recursive function as parameters in which case the system keeps the necessary state on the stack. Since the stack is relatively limited in size you want to make sure that you don't need too much context in recursive functions with deep call stack.

Since you probably don't want to require the user to pass in some internal context, the find() function in the the interface would probably just delegate to the recursive function providing the necessary context. For example:

int find(int j, int i) {
    if (15 < i) {
        return i;
    }
    ++j;
    return i * find(j, j + 1);
}
int find(int value) {
    return find(10, value);
}

(I'm not sure if I got the desired logic right because I didn't quite get what the function is meant to do...).

Upvotes: 1

user1708818
user1708818

Reputation: 75

Do you need a member variable?

Hope the following code helps.

Best regards Sam

class myClass{
  public 
  myClass() {
   m_j = 10;
  }

  private:
   int m_j; // private member variable for find algorithm; 


  int find(int i) {
    if(i>15)
      return i;
    m_j= m_j+1;
    return i * find(m_j+1);

   }

};

Upvotes: 1

Related Questions