I have three classes in total for my game engine, an abstract IComponent class in which all components inherit from it, a component class (for this example I will use RenderComponent), and a ComponentManager. I want the ComponentManager class to be able to use the constructor of RenderComponent, but I don't want any other classes to create an instance of RenderComponent, but I don't want to use 'friend' since I want customer user components to inherit from IComponent and automatically be used in the ComponentManager without being allowed to instantiate their own. The code example shows vaguely the behavior I want to occur:
class GameObject;
class IComponent
{
private:
IComponent() { }
~IComponent() { }
public:
GameObject* Parent;
}
class RenderComponent : IComponent
{
public:
RenderComponent() { }
~RenderComponent() { }
}
class ComponentManager
{
public:
ComponentManager() { }
~ComponentManager() { }
// normally this would be a template function, but for the sake of this example I will directly use RenderComponent
RenderComponent* CreateComponent()
{
// this would not throw a compiler error
return new RenderComponent();
}
}
int main()
{
ComponentManager manager;
// even though the constructor of RenderComponent is public, this would throw an error
RenderComponent* render = new RenderComponent();
// this however would work perfectly fine
RenderComponent* render = manager.CreateComponent();
}
To reiterate, I want it so that there is minimal user effort to creating components. The other option of course is to have the constructor for both public but have it so that although you can create a component wherever you want, it will be useless.
First I want to thank R Sahu for providing his answer, but the in his example would still allow the user to do what I wanted to avoid in the first place, randomly be able to create an instance of a component:
IComponent* component = new RenderComponent();
And now I realize that what I wanted is impossible, there is no way to restrict access of the constructor/destructor to the user without it also restricting access to the ComponentManager. So either my implementation is wrong or incomplete (which is unlikely but possible) or I'm asking for something that is illogical (the most likely answer).
So instead I just opted for having everything public, and just making randomly created components useless, and in the documentation of my engine I will describe that you have to use GameObject::AddComponent() in order to create and use components.
Thanks.