Skip to main content
GameDev.net gamedev.net
🔒 Locked

polymorphism and types

Started by Dragon_Strike May 18, 2008 at 5:04 AM 1 replies 550+ views
Original Post
Dragon_Strike
Dragon_Strike
im using C++ and ive got something like this.. class A{}; class B1 : public A{}; class B2 : public A{}; std::vector as; for (int n = 0; n as.size(); ++n) { /* pseudo if ( as[n] is instance of B1) do something if ( as[n] is instance of B2) do something else do something */ } how would i do this? i could test with a dynamic_cast each time.. but that seems a bit slow?
CmpDev
CmpDev

class A{virtual ~A(){}virtual void do_something() = 0;};class B1 : public A{void do_something();};class B2 : public A{void do_something();};std::vector<A*> as;for (std::vector<A*>::iterator i = as.begin(); i != as.end(); ++i){(i*)->do_something();}


Or if the function is external to the class use double dispatch.
ToohrVyk
ToohrVyk
Quote:
Original post by Dragon_Strike
im using C++ and ive got something like this..


Yes, you can achieve this with a dynamic_cast:

for (int n = 0; n < as.size(); ++n){  A* a = as[n];  assert (a);  if (B1* b = dynamic_cast<B1*>(a))    foo(b);  else if (B2* b = dynamic_cast<B2*>(a))    bar(b);  else    qux(a);}


Obviously, the operation done inside the for-loop is independent of the loop itself, meaning that basic refactoring rules will involve extracting the operation into its own method:

void frobnicate(A* a){  assert (a);  if (B1* b = dynamic_cast<B1*>(a))    foo(b);  else if (B2* b = dynamic_cast<B2*>(a))    bar(b);  else    qux(a);}std::for_each(as.begin(), as.size(), frobnicate);


But then, a function whose only purpose is to dynamic-dispatch a call based on the type of a given object should always be refactored toeither a virtual member function or a visitor:

class A { virtual void frobnicate() { qux(this); } };class B1 { void frobnicate() { foo(this); } };class B2 { void frobnicate() { bar(this); } };void frobnicate(A* a) { assert(a); a -> frobnicate(); }std::for_each(as.begin(), as.size(), frobnicate);

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.