c++ – How Utility functions can be shared across various classes? – Education Career Blog

I had a class Display with 2 utility functions getDate and getTime like below.

class Display
  void getDate(char *pDate); //Utility functions for converting to custom format
  void getTime(char *pTime);

Later, In other class called Retriever also, i needed the same Utility functions getDate and getTime. I do not want to make getDate and getTime functions global(Or C like functions), to avoid accidental usage of these functions(which are specific to these 2 classes). Even wrapping them in namespace won’t prevent accidental usage.

Display and Retriever are dissimilar classes. Can’t use inheritance between them. Can’t use Composition and aggregation as the lifetime of the objects of those classes will be different. They do not exist together(at same time).

Is there any good way of moving Utility functions out of Display and use them in both classes Display and Retriever ?
Is it good to put getDate and getTime in seperate class called Utilities and use object of it in classes Display and Retriever ?


Based on your additional info in the commentary/discussion, that e.g. getDate doesn’t depend on instance data, getDateand getTime should not be non-static member functions. Ideally they should be freestanding functions. Perhaps in a namespace.

Put them, and other related stuff, in its own module.

It can be a pure headerfile module, or a separately compiler module consisting of a headerfile and an implementation file.

Put the functions in a namespace like e.g. timeutil, or the name of a library, whatever.

And I recommend changing them to return std::string instead of taking raw pointer arguments, e.g.

#include <string>

namespace timeutil {
    std::string timeString();
    std::string dateString();

Cheers & hth.,


I think that using namespace will be most appropriate. You can choose name for that namespace so that everyone be aware of it purpose:

namespace DisplayRetrieverImplementation {
  void getDate(char *pDate); //Utility functions for converting to custom format
  void getTime(char *pTime);


You could make your functions private static members of another class. And make Display and Retriever friends of that class.

Leave a Comment