Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where should I implement this "private" helper function?

Tags:

c++

My class definition is spread across headers and source files:

// T.hpp

class T {
   public:
      void foo();
};

// T.cpp

void T::foo() {

}

If T::foo needs to make use of some helper function that need be visible only to T, which of the below solutions is best?

1. Private member

// T.hpp

class T {
   public:
      void foo();
   private:
      void helper();
};

// T.cpp

void T::foo() {
    helper();
}

void T::helper() {
}

2. Free function accessible only in class definition's TU

// T.hpp

class T {
   public:
      void foo();
};

// T.cpp

namespace {
    void helper() {}
}

void T::foo() {
    helper();
}

Is there any difference except that with the former I will end up with more functions in the header file?

like image 581
NoSenseEtAl Avatar asked Jan 05 '12 17:01

NoSenseEtAl


People also ask

Should helper functions be private?

You should make a function private when you don't need other objects or classes to access the function, when you'll be invoking it from within the class. Stick to the principle of least privilege, only allow access to variables/functions that are absolutely necessary.

How do you use the helper function?

A helper function is a function that performs part of the computation of another function. Helper functions are used to make your programs easier to read by giving descriptive names to computations. They also let you reuse computations, just as with functions in general.


1 Answers

Prefer free, non-friend functions over member functions, because these have less access to class members than member functions, and therefore have less of a chance to introduce bugs.

If the function is completely outside the interface scope then also put it in an unnamed namespace in the implementation file. This will reduce the chance of bugs even further, because other translation units will not be able to call the function.

Another advantage you get with a non-friend in an unnamed namespace is that there's less of a chance you change the header (since there's one less entity in there). Changing a header file often slows down build times considerably, because of the compile-time dependencies. Private or not, you'll probably have a number of translation units depending in terms of compilation on everything in the header.

like image 143
wilhelmtell Avatar answered Nov 15 '22 14:11

wilhelmtell