How do I determine the type of a class that is related to another class dynamically?
I have figured out a solution, the only problem is that I ended up having to use a define that has to be used in all of the derived classes.
Is there a simpler way to do this that doesn’t need upkeep for ever class that is added?
Things to note: both the class and the related class will always have their respective base class, the different classes can share a related class, and as in the example I would like the control class to own the view.
This is what I have now. The only thing I have to upkeep is the switch, but I would like to have it so I only need to add code insted of going back and changing it.
#include <iostream>
#include <string>
class model
{
public:
model( int id ) : id(id) {}
int id;
};
class view
{
public:
view( model *m ) {}
virtual std::string display()
{
return "view";
}
};
class otherView : public view
{
public:
otherView( model *m ) : view(m) {}
std::string display()
{
return "otherView";
}
};
class control
{
public:
control( model *m ) : m_(m), v_( createRelated() ) {}
~control()
{
delete v_;
}
std::string display()
{
if ( v_ )
return v_->display();
return "No view";
}
view *createRelated()
{
switch( m_->id )
{
case 0:
return new view( m_ );
case 1:
return new otherView( m_ );
default:
return NULL;
}
}
model *m_;
view *v_;
};
int main( void ) {
model m(0);
model om(1);
model nm(2);
control c1( &m );
control c2( &om );
control c3( &nm );
std::cout << c1.display() << std::endl;
std::cout << c2.display() << std::endl;
std::cout << c3.display() << std::endl;
}
A possible solution would be to change model to accept a pointer to a function that creates the related class, instead of passing an ‘id’:
Each of
viewclasses to provide a static method that creates an instance of itself:Then ‘createRelated()’ would become:
Example use:
Hope that helps.