Alexandru Kis
Alexandru Kis

Reputation: 127

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

Upvotes: 3

Views: 94

Answers (2)

You have to cast these objects:

cry(static_cast<B*>(weener));
cry(static_cast<C*>(wooner));

Otherwise compiler will be looking for cry function which takes A* as argument (because weener and wooner were declared as type of A* indeed).

Upvotes: 0

Paolo M
Paolo M

Reputation: 12757

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.

Upvotes: 2

Related Questions