Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class variable accessible to one function or a static variable in member function that is still object aware

Tags:

c++

A static variable in a member function is a class level variable, meaning that all class instances access the same variable.

class foo{
 int doingSomething(){
   static int count =0;
   static int someValue=0
   count++;
   if(count%10 == 0){
     someValue *= counter;
     }
   someValue += counter;
   return someValue * 2;
 }
}

I want a way to count the number of times count() was called in each instance of foo separately, i can do this :

class foo{
 int count;
 int someValue;
 int doingSomething(){
   count++;
   if(count%10 == 0){
     someValue *= counter;
 }
 someValue += counter;
 return someValue * 2;
}

but my problem with this approach is that count and somevalue is only used and accessed in foo by doingSomething(), so there is no reason for it to be a member variable, since it opens the door to it modified and used by other class member function, and i want to prevent that. is there a solution that i am missing ?


EDIT 1: The idea is to count the number of time that doingSomething() was called in each instance of Foo, and this value will be used only by 'doingSomething()' to compute other values, which will be different for each instance.

Why? doingSomething() compute a int someVariable the first time is called, then stores it for later use, this stored value is used by doingSomthing() 10 times with every call, every 11calls int someVariable is recalculates and this new value is used...process repeated indefinitely.

like image 621
InsaneBot Avatar asked Jul 14 '26 09:07

InsaneBot


2 Answers

you can hide your counter in a base class

class base_foo
{
public: 
 void doSomething()
 {
     counter++;
     //other fun stuff
 }

private:
   int counter;
};

class foo : base_foo
{
public:
    foo()
    {
        doSomething();
    }
// your other code
};
like image 108
RedOctober Avatar answered Jul 16 '26 00:07

RedOctober


One way I could see you doing this is with a std::map. You could have a static std::map<class_name*, int> in the function and every time the function is called use operator[] with this and increment the int part.

class Foo
{
public:
    void bar()
    {
        static std::map<Foo*, int> counter;
        counter[this]++;
    }
};
like image 40
NathanOliver Avatar answered Jul 16 '26 01:07

NathanOliver



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!