Here is a simplified example (OnlineGDB):
#include <iostream>
using namespace std;
class Base {
public:
virtual ~Base() {}
virtual int test(Base* parent) = 0;
};
class Test : public Base {
public:
~Test() {}
int test(Base* parent) { return 10; }
int test(Test* parent) { return 20; }
};
int main(int argc, char* argv[]) {
Test* test = new Test();
Base* base = test;
cout << test->test(test) << endl; // prints 20
cout << base->test(test) << endl; // prints 10
return 0;
}
I would expect both calls to return 20, because the argument is of type Test, but the second call returns 10.
I know I could do dynamic_cast<Test*>(base)->test(test) and it works again, but in reality I have more classes that are derived from Base. Of course I could do sth. like this:
auto test1 = dynamic_cast<Test*>(base);
if (test1) {
test1->test(test);
}
auto test2 = dynamic_cast<Test2*>(base);
if (test2) {
test2->test(test);
}
...
But for any new class derived from Base this would need to be adjusted and there are multiple sections in the code that have to do this.
Is there any way, I can keep the base->test(test) or sth. similar to get the "right" value based on the argument type?