Max
Max

Reputation: 6239

Add a list of a class to another class

I'm trying to create a master-slave scenario where the first class contains a list of all the other sub classes. I've created two classes.

If my master class is ControllerDetail and my sub class is ControllerPOD: public ControllerDetail....can I create a list of all ControllerPOD's from the Controller Detail class?

I've tried creating std::list<ControllerPOD> cps; in the private section, but that obviously doesn't work.

Thanks!

Upvotes: 1

Views: 1714

Answers (2)

CashCow
CashCow

Reputation: 31445

It is slightly ambiguous what you are trying to do here. ControllerDetail is a class not an object, and you will have lots of them, one for each ControllerPOD.

So if you want it to have a list it would have to be static.

Now suppose you want ControllerDetail to have a static list of all the objects currently existing that derive from it. So we will have this:

class ControllerDetail
{
   typedef std::list<ControllerDetail * > list_type;
   static list_type instances;
   list_type::iterator m_iter; // will become apparent later
};

In our constructor of ControllerDetail we will add our instance to the list.

ControllerDetail::ControllerDetail() 
{
    instances.push_back( this );
    m_iter = instances.back(); // iterator that holds our object
}

In our destructor we remove ourselves from the list

ControllerDetail::~ControllerDetail()
{
    instances.erase( m_iter );
}

And obviously you may have to handle thread-safety issues in all of this but you can iterate through the list and see all the current instances of the class. As ControllerPOD derives from ControllerDetail, when it is constructed it will get added too.

If you only want specific sub-classes to be added, you can use some kind of flag in the constructor of ControllerDetail as to whether to add itself.

It is generally better for a class to not know the classes that derive from it.

Now if ControllerPOD is not really a type of ControllerDetail then your ControllerDetail would have a list of ControllerPOD* instead, your ControllerPOD constructor would instead add itself and remove itself from the list, and you would have to sort out your "access" to allow it to do so, but the principle is the same.

If your ControllerPOD is passed a "parent" object which is a ControllerDetail, then the parent would have the list as a member and your ControllerPOD would add itself and remove itself from the parent's list. This assumes the parent outlives the child.

If we see what you really want to do, we can look at your class design a bit more clearly.

Upvotes: 1

Armen Tsirunyan
Armen Tsirunyan

Reputation: 133024

Yes, you can:

class ContollerPOD; //forward declaration
class ControllerDetail
{
   ...
   private:
   std::list<ControllerPOD> cps;
};

class ControllerPOD: public ControllerDetail
{
   ...  
};

Upvotes: 2

Related Questions