1

A college at work created a class with only static methods. Because he wants to avoid instantiation, he added a (private) constructor. That's fine so far. But the constructor is only declared and has no implementation. Thus you will get an "undefined reference" when using it once.

Imho it must be enough to make the constructor private - and declarations without implementation is ugly. What is your opinion about this?

Charly
  • 1,270
  • 19
  • 42

2 Answers2

1

I see your concern.

In fact, making a copy-constructor private and then leave it unimplemented, is a common practice, and it is certainly necessary in certain cases. This has led to the definition of a well-known C++ idiom, the Non Copyable Mixin to give it more "visibility". But even when the non copyable mixin is not used and the solution is applied locally, it is IMO perfectly acceptable (because it is a known idiom).

In your specific case, since as I understand we are not talking about copy constructors, but any constructors (the class is just a container for some static methods and you do not want it to be initialized), I think using a namespace and declaring your functions within it would be a better solution.

sergio
  • 68,819
  • 11
  • 102
  • 123
0

Actually instantiating such objects would not cause any harm - program behavior will not change. If you still want to prohibit instantiation, then yes, you better not implement the constructor. If you have an empty constructor it might be called from within friends of the class and from within member functions of the class. See this question for details.

Community
  • 1
  • 1
sharptooth
  • 167,383
  • 100
  • 513
  • 979
  • But for me it looks like an error: Forgetting to implement it. Isn't makeing it private much more explicit?? The boost way is to provide a base-class noncopyable - so it hides this hack and is also some kind of documentation. – Charly Jun 20 '12 at 12:40
  • @Charly: Yes, both make it private and unimplemented and add a comment like "the class should not be instantiated" above the constructor declaration. – sharptooth Jun 20 '12 at 12:49