Priority on parameters using subclasses

Hello people,

I'd like to make many child classes (say B, C, D, ... with a common parent A) respond the same message "doSomething" using polymorphism in this way:

A::doSomething(A var){ // Any child will inherit this method
// it will do nothing in this case
}

B::doSomething(B var){
// does something
}

B::doSomething(A var){
// it will do nothing in this case
}

C::doSomething(C var){
// does something
}

C::doSomething(A var){
// it will do nothing in this case
}

And so on... I would like to have that priority on the message 'doSomething', so any child will respond to its specific message first (containing the same parameter type as itself) and in the default case it will respond the general parameter message.

In my case, if I do aVarB.doSomething( anotherVarB ) it always uses the method B::doSomething(A var); I'm not able to force it to go through the most specific function :/

How can I do this? Thanks in advance!
Last edited on
Cannot reproduce:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
struct A
{
    virtual void doSomething(A var)
    { std::cout << "A(A)\n"; }
};

struct B : public A
{
    virtual void doSomething(A var)
    { std::cout << "B(A)\n"; }

    virtual void doSomething(B var)
    { std::cout << "B(B)\n"; }
};

struct C : public A
{
    virtual void doSomething(A var)
    { std::cout << "C(A)\n"; }

    virtual void doSomething(C var)
    { std::cout << "C(C)\n"; }
};

int main()
{
    B b, bb;
    b.doSomething(bb);
}
B(B)
Show an example illustrating your problem.
Last edited on
Topic archived. No new replies allowed.