What is the best way to create related types at runtime?

Posted by SniperSmiley on Stack Overflow See other posts from Stack Overflow or by SniperSmiley
Published on 2011-11-18T15:52:23Z Indexed on 2011/11/18 17:51 UTC
Read the original article Hit count: 289

Filed under:
|
|

How do I determine the type of a class that is related to another class at runtime?

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 the define or a copy paste?

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.

#include <iostream>
#include <string>

class model;

class view {
public:
  view( model *m ) {}
  virtual std::string display() {
    return "view";
  }
};

#define RELATED_CLASS(RELATED)\
typedef RELATED relatedType;\
virtual relatedType*createRelated(){\
return new relatedType(this);}

class model {
public:
  RELATED_CLASS(view)
  model() {}
};

class otherView : public view {
public:
  otherView( model *m ) : view(m) {}
  std::string display() {
    return "otherView";
  }
};

class otherModel : public model {
public:
  RELATED_CLASS(otherView)
  otherModel() {}
};

class control {
public:
  control( model *m ) : m_(m),
      v_( m->createRelated() ) {}
  ~control() { delete v_; }
  std::string display() {
    return v_->display();
  }
  model *m_;
  view  *v_;
};

int main( void ) {
  model m;
  otherModel om;

  model *pm = &om;

  control c1( &m );
  control c2( &om );
  control c3( pm );

  std::cout << c1.display() << std::endl;
  std::cout << c2.display() << std::endl;
  std::cout << c3.display() << std::endl;
}

© Stack Overflow or respective owner

Related posts about c++

Related posts about types