I am not sure my title is verbose enough but I don't know how to better put it in words. Basically I want to have, for example, these classes:
class A {};
class B : public A{};
class C : public A{};
these two functions:
void cry(B* param){ cout << "Wee"; };
void cry(C* param){ cout << "Woo"; };
and this piece of code:
int main()
{
A* weener = new B();
A* wooner = new C();
cry(weener);
cry(wooner);
}
and I expect this output:
wee
woo
But this, in my case, this won't even compile. Is this possible? If yes, what is the correct approach?
PS: The cry function must be outside the classes
A simple workaround could be defining a single cry function that select its behavior depending on the dynamic type of its parameter:
void cry(A* param)
{
if( dynamic_cast<B*>(param) ) //do something
;
else if( dynamic_cast<C*>(param) ) // do something else
;
}
Obviusly, this is resolved at runtime and comes with a (often negligible) performance cost.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With