semi-private constructors and inheritance

J

Jan Althaus

I'm trying to solve the following problem:
How do I let the user register a class with another class, without him
being able to instantiate it?

In a more practical way:
The user derives from a Module class, which is able to perform actions
which must only be performed during a given scope. This scope is
managed by a different class, let's call it Manager. Because the
derived class is not known beforehand, the user must be able to
register the new type, however he must not be able to instantiate it
himself (as that would defeat the whole purpose of managing it's
scope).

If it weren't for the polymorphism, one way to do this would be to
have a manager method like this:

template <class T> void RegisterModule()
{
m_modules.push_back( new T() );
}

To limit access one could make Module's constructor private and
befriend Manager.
So the usage would look something like this:

Manager::RegisterModule< MyModule >();

Given that people can derive from Module however, this means that the
derived classes would have to, themselves, implement similar
restrictions and again, befriend the manager themselves etc.
All of which would make deriving from Module rather error prone and
tedious.
Can anyone think of a cleaner way to implement a similar model?
Ta!

Jan
 
J

Jan Althaus

This allows Creator to create objects of types derived from Base, but not
for the user to create them, even though he defines them. But I question
whether protecting the user from himself is really that big of a deal.

Ah, clever! That actually seems both very straight forward to derive
from and implement. Ta!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,169
Messages
2,570,919
Members
47,460
Latest member
eibafima

Latest Threads

Top