Search code examples
c++classstructprivate-membersparam

C++ passing in a class member item to a member function


What are the consequences (other than being poor code) of passing in a member item unnecessarily to a member function:

struct foobar
{
  char * arr; //properly initialized to SIZE at some point
}

class foo
{
  public:
    void bar(foobar&);
    foobar barfoo;
};


void foo::bar(foobar& barf)
{
    cin.get(barf.arr, SIZE, '\n');
    cin.ignore(100, '\n');
}

Is there any reason not to eliminate the parameters in bar altogether and just call barfoo directly? What are the consequences of NOT doing so, if any?


Solution

  • There is a slight overhead with passing the parameter, so if you will never call that method with another member, then you can get rid of the parameter. If you might need to do something like this in the future:

    class foo 
    { 
      public: 
        void bar(foobar&); 
    
      private/*(or still public)*/: 
        foobar barfoo;
        foobar barfoo2;
    
        void some_other_method() {
          //do stuff
          bar(barfoo);
          bar(barfoo2);
    }; 
    

    Then I would leave it alone.