Jump to content
  • Advertisement

Archived

This topic is now archived and is closed to further replies.

Caesar

Is RTTI the solution?

This topic is 6012 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi,
  
class A{...};
class B:public A{...};
class C:public A{...};

class D{
protected:
  A *a;
public:
  CreateA(A *b);
};
  
Now I pass an A/B/C instance as parametr to D::CreateA and I want it to create a new instance (the a member variable) of the same class as b is. I think temeplates could solve this, but I don''t want to use them. Maybe RTTI could be the solution, but I''ve absolutely no idea on how to use it (a tutor link apperciated). And I don''t want to use some kind of determining variable just because it''s not very clean (although nearly the same as RTTI) and because if a new class derived from A turns up, I don''t want to add a new case to the switch that would be. Thanks

Share this post


Link to post
Share on other sites
Advertisement
Sounds like a job for the virtual constructor/virtual copy constructor.

  
class A
{
public:
virtual A* create(void)
{
return new A;
}
virtual A* clone(void)
{
return new A(*this);
}
};
class B : public A
{
public:
virtual B* create(void)
{
return new B;
}
virtual B* clone(void)
{
return new B(*this);
}
};
class C : public A
{
public:
virtual C* create(void)
{
return new C;
}
virtual C* clone(void)
{
return new C(*this);
}
};
class D
{
protected:
A* a;
public:
CreateA(A* theA)
{
a = theA->create();
// or, if you want a copy instead

a = theA->clone();
}
};

Some compilers (e.g. VC++ 6) don''t like the different return types, in which case all the clone and create functions will have to be declared as returning A* instead.

Share this post


Link to post
Share on other sites

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!