I am writing a library in C++. I am trying to have a clear separation between the public header files and the internal implementation, to make the library as easy to use as possible.
I have a class (let’s call it
Information) whose instances I want to return to the user. This class is basically an immutable data container, it is comprised exclusively of private, constant attributes and their getter methods. I want to make it clear to the user that they are not supposed to instantiate objects of such class themselves, and what better way than to not give them the option?
I have thought of making
Information an abstract class in the header file. That way I can document all of its methods while not providing any constructors. I can internally have a child class of
InformationImpl) whose instances I can then return to the user. Unfortunately, this means I’d need to return these instances as heap-allocated objects, which I feel adds complexity (working with pointers is easier with smart pointers, but still).
Another option would be making the constructor private and adding an internal class as a friend class. I dislike this as it generates coupling and leaks internal classes into the public API.
Is there another way in which I can have a class be part of the public API while keeping the user from instantiating it?
EDIT: The question has been closed as a duplicate, but I don’t think it is. The context of this question revolves around constructing an API, and avoiding coupling and unnecessary polymorphism. That is missing from the question which this one supposedly duplicates, and changes the acceptable answers drastically.
Source: Windows Questions C++