This code compiles.
#include <bits/stdc++.h>
using namespace std;
class PA {};
class PB {};
class A {
public:
void foo(PA) { cout << "A PA" << endl; }
void foo(PB) { cout << "A PB" << endl; }
};
class B : public A {
public:
// void foo(PA) { cout << "B PA" << endl; }
};
int main() {
B b;
PB PB;
b.foo(PB);
return 0;
}
Uncomment line 16 and the compilation will fail.
foo.cpp: In function ‘int main()’:
foo.cpp:22:9: error: cannot convert ‘PB’ to ‘PA’
22 | b.foo(PB);
| ^~
| |
| PB
foo.cpp:16:12: note: initializing argument 1 of ‘void B::foo(PA)’
16 | void foo(PA) { cout << "B PA" << endl; }
|
This problem can be solved by using A::foo;. But I ran into a situation where there are multiple polymorphic functions in the base class. using for each of them seems silly.
Is there a way to import all functions of the base class like using A::*;? Or should this not happen at all and I should re-architecture the code?
Thanks!
Edit:
I noticed that many comments mention the lack of polymorphism here. Isn't ad hoc polymorphism polymorphic?
I didn't use virtual functions here because I don't need to access subclass methods through the base class. This is an additional capability. I don't think it is relevant to this problem.
As mentioned above, I can use
usingto introduce hidden names. But this makes me need to repeatusingbase class method in each subclass, somewhat breaking the reduction in programming complexity that my abstraction brings. This is what confuses me.