Home > Software engineering >  Using private member variable as private function parameter
Using private member variable as private function parameter

Time:08-02

class C
{
public:
  void clearWithParam()
  {
    clearImage(image, size);
  }
  void clearWithoutParam()
  {
    clearImage();
  }
private:
  unsigned char* image;
  size_t size;

  void clearImage(unsigned char* image, size_t& size)
  {
    for(int i=0; i<size; i  )
    {
      image[i] = 0;
    }
  }

  void clearImage()
  {
    for(int i=0; i<this->size; i  )
    {
      this->image[i] = 0;
    }
  }
}

I found there are two ways of implementing private methods. Two clearImage()s here do exactly the same thing. However the first one takes private members image and size as its parameters, and the second access the private member directly. Which one is more preferred?

CodePudding user response:

By the rules that govern scope, the function args are given preference over the members of the same name. Since the instance remains accessible, you can still access the member variables via things like this->image.

Some people prefer to try and avoid such ambiguity and have established a fairly popular (to the point of it being adopted into c code quality requirements in some places) naming convention of having all members begin with a m_ prefix. Great time savings compared to typing this-> and reading it too. When code is clear yet more fits on a screen at once, it tends to reduce scrolling required for review too.

Furthermore, if a function needs nothing from the instance, consider adding the static modifier.

  • Related