1

i have an accounts class from that i have 3 types of accounts savings, credit, and homeloan.

i created a binary search tree to hold all the accounts as type account

how do i now access the methods of the subclasses depending on the type of object?

have resolved all errors with syntax and codeing but this.

been racking my head for 2 days . does anyone know how this is done ?

Ryan
  • 13
  • 3
  • 4
    Perhaps you can show the code that you have so that people can help you with your specific problem. – James McNellis Sep 09 '10 at 15:50
  • My guess is you're storing the accounts by base class type, rather than pointer to base class hence slicing the objects. – John Dibling Sep 09 '10 at 16:59
  • 1
    John makes a good point - when you pass the objects around, do it by pointer, otherwise you'll slice the objects. http://stackoverflow.com/questions/274626/what-is-the-slicing-problem-in-c – Ragster Sep 10 '10 at 08:53

1 Answers1

3

The simple answer is, if you need to access the derived class functionality from a base class pointer, you have a design problem. In principle, you shouldn't need to know. If you do, something is wrong. You're supposed (in a pure sense) to call virtual functions from the base class interface, and have the derived classes implement their overrides such that they perform correctly.

Now then, sometimes, practically, you have to. So there is the possibility of a downcast. If you have Run Time Type information in your build, you can do a dynamic_cast<type*> and if the pointer you get back is non-null, then you have an instance of that type.

If you do go down this path, wrap it in something neat and don't let it proliferate - it can get messy. I suggest you see if there isn't a better way, using polymorphism.

Have fun!

Ragster
  • 717
  • 3
  • 6
  • I had a few things worked out but you covered the idea without getting too technical, and you were a little quicker at typing. :P – SubSevn Sep 09 '10 at 15:57
  • Thanks Sven :) So often, I have an answer in progress, and someone posts before I do. It's down to the second to get yours in first sometimes! I suppose it's good that there are so many people anxious to help. – Ragster Sep 09 '10 at 16:01