Even though ptr is a pointer to Base, the correct method is called based on what it points to. |
I see but you must change the pointer every time you want to call method from different instance. The only advantage here is that you have only one pointer which is only one declaration of pointer. Edit:
and another advantage I see now is that if you want call these methods from superior function, you can do it by one line; just calling ptr->myMethod... but there must be some argument in the superior function, something like superiorCall(type) and some mechanism which will control which method to use. Which class type to call ....
This is on page 2:
1 2 3 4
|
ECBase& source =
(data->type == CONDITION) ?
static_cast<ECBase&>(t->conds[data->index]) :
t->effects[data->index];
|
The first is type Condition the second is type Effect, and you can both pass to one source to call them later with source.toBuffer(data);
.
But I could discard the virtual keywords in your code and then call:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
void myFunc()
{
Base aBase;
Derived1 aDerived1;
Derived2 aDerived2;
Base* ptr = &aBase;
Derived1* ptr1 = &aDerived1;
Derived2* ptr2 = &aDerived2;
ptr->myMethod(); // Outputs "Base class"
ptr1->myMethod(); // Outputs "Derived1 class"
ptr2->myMethod(); // Outputs "Derived2 class"
}
|
So this is simple too, and I don't need to use later building. It also looks more clear and you know that these methods are different even that they have same name because they are in different classes.
Another note:
I think real advantage of the polymorphism should be in the fact that if you pass different types (in my example I use three types: TRIGGER, EFFECT, CONDITION) so you would save some coding because you could use one method or one set of methods to manipulate different types... but I am still not sure with it.
Maybe this would be simple changeable with templates. They also enables you to define methods with same name, but using different types. I mean template specialisation. But I think this would mean different concept / design. Because that things which are now devided to 3 files - three different classes would have to be in one file as one big template - I think it would be very unclear and hard to type such big template. Because as far as I understand templates, they should simplify the programming, not to make them more complicated :-)