C++ superclass Array yet access subclass methods? - c++

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 ?

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!

Related

Using an interface, and telling it all implementors _will also_ inherit from a common base class

Sometimes, you invent an interface to say that a certain type of object supports a certain type of behavior. For example, both Dog and ScaryDog have the MeleeAttacker interface.
But now say I pass a MeleeAttacker* into some function,
void Attack( MeleeAttacker* attacker, Living *victim ) ;
Because MeleeAttacker is separated from the hierarchy, I can't access the vitals of attacker -- I cannot access members of Living for attacker even though I know attacker is a Living. Because of how I constructed the hierarchy, I know that MeleeAttackers will always be inheritors of the common class WarmBlooded. But the code doesn't know that. My question is, how can I tell the code that?
I think I have just confused things by introducing the MeleeAttacker interface, but I didn't want to crowd the base WarmBlooded class with functions that won't be implemented in some branches of the hierarchy (for example, the "implementation" for a Bird's melee attack might be {} (nothing)).
Why not simply cast your argument to a Living * using dyanmic_cast? You know it will, since you guarantee that by virtue of your concrete classes implementing the latter whenever the former is implemented.
Basically the idea is kind-of-like queryInterface in COM, only you don't have to actually implement queryInterface yourself in each class, since you know the cast will work, and you don't have to implement graceful handling in your calling code, since, again, you know the cast will succeed.

C++, avoid RTTI and the visitor pattern, is it possible?

I've been looking at some related threads but still don't find anything that answers the following question.
Let's say I have a hierarchy of classes (e.g. Widgets, HTML element) that form a tree structure. When I walk through the tree or look for a concrete element based on its ID I get a pointer to the base class (the tree algorithms only know about the base class).
Then, based on the type (the base class has a field that identifies the type) I perform a dynamic_cast in order to get a pointer to the concrete type. I've been thinking about ways to avoid this. The only thing that comes to my mind is the visitor pattern. But don't like very much this pattern.
Are there other ways/patterns to search/iterate nodes and get a pointer to the concrete class without using RTTI nor the visitor pattern?
Your approach doesn't sound like a good idea. Mostly because you have to do all the considerations before the runtime.
What you want to do is basically have the specific properties of a object listed and accessible. With dynamic casting this is possible but hardly elegant - since you have to write a trainload of switches and hardcode each and every possibility in advance so you can use it at runtime.
The solution I'd recommend as usual is the Qt framework. You can list the properties for each object at runtime, access a specific property by its name string or index and even attach properties during the runtime that don't exist in the code. And all this is type agnostic, you don't need to know an object's type to know its properties, and lastly - Qt offers a significantly faster qobject_cast for QObject derived classes instead of dynamic_cast.
The meta system allows you to know the class name, the base class name, methods, enums, constructors and pretty much everything, so besides properties, it is a good source for accessing all the functionality, available to an instance.
It really depends on the implementation of the visitor pattern. Using dynamic_cast<> is one way, another might be to use a handcrafted RTTI by defining a virtual GetType() function which can be implemented in all the subclasses. Depending on the result of that function you can do different things.

Is there any way to avoid declaring virtual methods when storing (children) pointers?

I have run into an annoying problem lately, and I am not satisfied with my own workaround: I have a program that maintains a vector of pointers to a base class, and I am storing there all kind of children object-pointers. Now, each child class has methods of their own, and the main program may or not may call these methods, depending on the type of object (note though that they all heavily use common methods of the base class, so this justify inheritance).
I have found useful to have an "object identifier" to check the class type (and then either call the method or not), which is already not very beautiful, but this is not the main inconvenience. The main inconvenience is that, if I want to actually be able to call a derived class method using the base class pointer (or even just store the pointer in the pointer array), then one need to declare the derived methods as virtual in the base class.
Make sense from the C++ coding point of view.. but this is not practical in my case (from the development point of view), because I am planning to create many different children classes in different files, perhaps made by different people, and I don't want to tweak/maintain the base class each time, to add virtual methods!
How to do this? Essentially, what I am asking (I guess) is how to implement something like Objective-C NSArrays - if you send a message to an object that does not implement the method, well, nothing happens.
regards
Instead of this:
// variant A: declare everything in the base class
void DoStuff_A(Base* b) {
if (b->TypeId() == DERIVED_1)
b->DoDerived1Stuff();
else if if (b->TypeId() == DERIVED_2)
b->DoDerived12Stuff();
}
or this:
// variant B: declare nothing in the base class
void DoStuff_B(Base* b) {
if (b->TypeId() == DERIVED_1)
(dynamic_cast<Derived1*>(b))->DoDerived1Stuff();
else if if (b->TypeId() == DERIVED_2)
(dynamic_cast<Derived2*>(b))->DoDerived12Stuff();
}
do this:
// variant C: declare the right thing in the base class
b->DoStuff();
Note there's a single virtual function in the base per stuff that has to be done.
If you find yourself in a situation where you are more comfortable with variants A or B then with variant C, stop and rethink your design. You are coupling components too tightly and in the end it will backfire.
I am planning to create many different children classes in different
files, perhaps made by different people, and I don't want to
tweak/maintain the base class each time, to add virtual methods!
You are OK with tweaking DoStuff each time a derived class is added, but tweaking Base is a no-no. May I ask why?
If your design does not fit in either A, B or C pattern, show what you have, for clairvoyance is a rare feat these days.
You can do what you describe in C++, but not using functions. It is, by the way, kind of horrible but I suppose there might be cases in which it's a legitimate approach.
First way of doing this:
Define a function with a signature something like boost::variant parseMessage(std::string, std::vector<boost::variant>); and perhaps a string of convenience functions with common signatures on the base class and include a message lookup table on the base class which takes functors. In each class constructor add its messages to the message table and the parseMessage function then parcels off each message to the right function on the class.
It's ugly and slow but it should work.
Second way of doing this:
Define the virtual functions further down the hierarchy so if you want to add int foo(bar*); you first add a class that defines it as virtual and then ensure every class that wants to define int foo(bar*); inherit from it. You can then use dynamic_cast to ensure that the pointer you are looking at inherits from this class before trying to call int foo(bar*);. Possible these interface adding classes could be pure virtual so they can be mixed in to various points using multiple inheritance, but that may have its own problems.
This is less flexible than the first way and requires the classes that implement a function to be linked to each other. Oh, and it's still ugly.
But mostly I suggest you try and write C++ code like C++ code not Objective-C code.
This can be solved by adding some sort of introspection capabilities and meta object system. This talk Metadata and reflection in C++ — Jeff Tucker demonstrates how to do this using c++'s template meta programming.
If you don't want to go to the trouble of implementing one yourself, then it would be easier to use an existing one such as Qt's meta object system. Note that this solution does not work with multiple inheritance due to limitations in the meta object compiler: QObject Multiple Inheritance.
With that installed, you can query for the presence of methods and call them. This is quite tedious to do by hand, so the easiest way to call such a methods is using the signal and slot mechanism.
There is also GObject which is quite simmilar and there are others.
If you are planning to create many different children classes in different files, perhaps made by different people, and also I would guess you don't want to change your main code for every child class. Then I think what you need to do in your base class is to define several (not to many) virtual functions (with empty implementation) BUT those functions should be used to mark a time in the logic where they are called like "AfterInseart" or "BeforeSorting", Etc.
Usually there are not to many places in the logic you wish a derived classes to perform there own logic.

C++ Different subclasses need different parameters

I'm looking for the best way to accomplish the following:
Background
I have a based class with a request() virtual method with different subclasses provide alternate implementations of performing the requests. The idea is I'd like to let the client instantiate one of these subclasses and pass in one of these objects to a subsystem which will call request() when it needs to. The goal is to let the client decide how requests are handled by instantiated the desired subclass.
Problem
However, if a certain subclass implementation is chosen, it needs a piece of information from the subsystem which would most naturally be passed as an argument to request (i.e. request(special_info);). But other subclasses don't need this. Is there a clean way to hide this difference or appropriate design pattern that can be used here?
Thanks
Make the base request() method take the information as argument, and ignore the argument in subclass implementations that don't need it.
Or pass the SubSystem instance itself to the handler, and let the handler get the information it needs from the SubSystem (and ignore it if it doesn't need any information from the SubSystem). That would make the design more extensible: you wouldn't need to pass an additional argument and refactor all the methods each time a new subclass needing additional information is introduced.
JB Nizet's suggestion is one possible solution - it will certainly work.
What worries me a little is the rather vague notion that "some need more information". Where does this information come from, what decides that? The general principle with inheritance is that you have a baseclass that does the right thing for all the objects. If you have to go say "Is it type A object or type B object, then do this, else if it's type C object do something slightly different, and if it's type D object, do a another kind of thing", then you're doing it wrong.
It may be that JB's suggestion is the right one for you, but I would also consider the option that "special_info" can be passed into the constructor, or be fetched via some helper function. The constructor solution is a sane one, because at construction time, obviously, you need to know if something is a A, B, C or D object that you are creating. The helper function is a good solution some other times, but if it's used badly, it can lead to a bit of a messy solution, so use with care.
Generally, when things end up like this, it's because you are splitting the classes up "the wrong way".

A concrete design case in C++, embedded AVR project

I have a design problem I pictured on a diagram below. There is a class Owner holding pointers to classes Switcher and Base. Switcher has a method, say Switcher::switch(Base* base) whose goal is to change Owner::Base's implementation from Child1 to Child2 or back if needed. I wouldn't like to implement this functionality in Owner, as it is complex enough already. The variables Switcher* Owner::switcher and Base* Owner::base are private in Owner.
Is there a design pattern for this? How would should I implement it? If written some simple code to implement it but I guess I'm having problems with access control, as switcher and base member variables are declared private. I can't tell for sure, as I cannot step-by-step debug the system (it's an embedded project). I'm also trying to implement it with linux-gcc to test what's wrong, but maybe there is a simple solution I I didn't think of, and hence the question here. I wouldn't like to use friend keyword, as I somehow have a feeling using it is a sign of bad design.
Why not access the base through switcher. That way, switcher can change base and owner will only see itself accessing the switch.
Otherwise, have switcher call a setbase(Base*) method in owner. The switching logic could then be handled in the switcher, but the access to the fields is in owner, where it belongs.
just to gain a bit of clarity, are child1 and child2 inherited from base? If so, how are you intending to "switch" them?
Im guessing your trying to avoid circular references?
EDIT: I don't think there is a design pattern that really matches up nicely to this problem, the closest I can think of, is maybe adapting the factory somewhat so that you can hand the base back, and ask for it in a different form.