Overloading a call function for a derived class parameter with a base class parameter
I'm not sure if my title is detailed enough, but I don't know how best to 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 that, in my case, it won't even compile. Is it possible? If so, what is the correct approach?
PS: cry function must be outside of classes
+3
source to share
2 answers
A simple workaround could be to define a single function cry
that chooses its behavior based 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 allowed at runtime and comes with (often negligible) runtime costs.
+2
source to share