Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling function overload for a derived class parameter with a base class parameter

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

like image 603
Alexandru Kis Avatar asked Jun 21 '26 12:06

Alexandru Kis


1 Answers

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.

like image 172
Paolo M Avatar answered Jun 23 '26 03:06

Paolo M