Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C++ conditions based on runtime polymorphic object's class

I’m trying to make some conditional actions depend on the type of polymorphic objects resolved at runtime.

Here is some pseudocode to illustrate what I mean:

class Base {
  //base class impl
} ;

class Foo : public Base {
  // foo class impl
}; 

class Bar : public Base {
  // bar class impl
};

int main() 
{
  std::vector<Base*> v;
  Base* A = new Foo();
  Base* B = new Bar();
  v.push_back(A); 
  v.push_back(B);  
 
  std::stack<Base*> s; 

  for (auto& ptr : v)
  {
    // push on stack if of type Foo, do nothing if of type Bar
  }
}

Here is an implementation of this idea in Java.:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

// for (...)
{
  if (component instanceOf Foo)
  {
    stack.push(component)
  }
}

What would be the correct way to implement this idea in C++?

>Solution :

This can be done with dynamic_cast:

if (auto* fooptr = dynamic_cast<Foo*>(ptr); fooptr != nullptr)
{
    stack.push(fooptr);
}

This of course requires that the classes really are polymorphic, and have at least one virtual function (which should be the destructor).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading