-2

I have three classes inherited from same parent class. and i have function that takes parent type(typical polymorphism) as parameter. How do i distinguish the true type of the object? Thanks

class Parent{}
class A : public Parent{}
class B : public Parent{}
class C : public Parent{}

void test(Parent &input){
/*
     how do i know the object is A, B or C?
     I want to perform some operations on the input
     but it's different depends on input's true type.
*/
}
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
Evan.zz
  • 155
  • 2
  • 10

2 Answers2

1

The standard solution is the usual for polymporphic classes: Virtual functions!

Create a pure virtual function in the Parent class, which is overridden and implemented in all the child classes. Then the test function just calls this function and the child-class implementations can do whatever is needed and specific for its own class.

No need to check the class, which is almost always a sign of bad design.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
0

Maybe chain of responsibility would be a good fit here. You pass the object received to a chain of children types and let the links in chain decide whether this object is for them to process if not then they will keep forwarding object to the next link in chain.

ThinkGeek
  • 4,749
  • 13
  • 44
  • 91