Using non-member methods in C ++

I have most of my classes split into two files (.h and .cpp). All of their methods (public, private or protected) are declared in the .h file and defined in the .cpp file.

However, sometimes I just need a quick helper method that is used by only one of the member methods. In these cases, is it possible to simply declare / define this method in the .cpp file as a non-member function without declaring it in the .h file?

What are the possible disadvantages of this approach? The one I see is that the definition of this method must precede its use in the .cpp file (if we do not want to use forward declaration). In addition, the IDE may have trouble finding these functions if they are completely in the .cpp file.

The reason I ask about this is because sometimes it seems like I am polluting the .h file with declarations of these methods that do not have access to the element data and are not used by any other class / file. It seems like I'm making really important declarations in the .h file, it's harder to find / read by entering these helper method declarations.

+4
source share
3 answers

Using a function other than a member is the best solution. Some even prefer non-member functions to member functions publicif this can be achieved. See Scott Meyer's article on this subject .

In the past days, I used the helper functions staticin the file area.

.cpp .

namespace
{
   // Helper class(es)
   struct Helper
   {
      ...
   };

   // Helper funtions
   type1 function1(...) { ... }

   type2 function2(...) { ... }
}

, type_info . , . namespace, .cpp.

foo.cpp:

namespace fooNS // Just append "NS" to the name of the cpp file
{
   // Helper class(es)
   struct Helper
   {
      ...
   };

   // Helper funtions
   type1 function1(...) { ... }

   type2 function2(...) { ... }
}

using namespace fooNS; // This allows the helper classes and functions
                       // to be used in the .cpp file without explicit use
                       // of the namespace.

.

+3

. , , , , .

, .

0

It's good enough that these helper function declarations do not create name conflicts with names from other header files, but this is not something you cannot handle.

A better approach is to use an anonymous namespace, and an even better approach is to use namespaces. This way you can be specific and do much more, for example. versions or even bind them to a specific class:

namespace foo_helper{ foofun(){} }
class foo{ 
// calls foo_helper::foofun()
};

Finally, you can use lambda functions for trivial tasks as part of the method for grouping.

0
source

Source: https://habr.com/ru/post/1618948/


All Articles