S
stf
Why does this code not compile?
#include <iostream>
using namespace std;
class A {
public:
virtual void myMethod(const string& s) const;
};
class B : public A {
public:
virtual void myMethod(int x) const;
};
void A::myMethod(const string& s) const {
cerr << "(A) myMethod: s is: " << s << endl;
}
void B::myMethod(int x) const {
cerr << "(B) myMethod: x = " << x << endl;
}
int main() {
std::string s("my string one");
B b;
b.myMethod(s);
return 0;
}
The error is:
$ g++ -Wall ./test-5.cpp -o test-5.out ./test-5.cpp: In function
‘int main()’:
../test-5.cpp:25: error: no matching function for call to
‘B::myMethod(std::string&)’
../test-5.cpp:18: note: candidates are: virtual void B::myMethod(int)
const
It looks that if I change:
b.myMethod(s);
to:
b.A::myMethod(s);
then it works OK. However this is bulls*t of course, because later
if someone implements B::myMethod(const string& s) const, the
purpose of virtual method will be defeated.
How to cope with this??!
Thanks!
STF
#include <iostream>
using namespace std;
class A {
public:
virtual void myMethod(const string& s) const;
};
class B : public A {
public:
virtual void myMethod(int x) const;
};
void A::myMethod(const string& s) const {
cerr << "(A) myMethod: s is: " << s << endl;
}
void B::myMethod(int x) const {
cerr << "(B) myMethod: x = " << x << endl;
}
int main() {
std::string s("my string one");
B b;
b.myMethod(s);
return 0;
}
The error is:
$ g++ -Wall ./test-5.cpp -o test-5.out ./test-5.cpp: In function
‘int main()’:
../test-5.cpp:25: error: no matching function for call to
‘B::myMethod(std::string&)’
../test-5.cpp:18: note: candidates are: virtual void B::myMethod(int)
const
It looks that if I change:
b.myMethod(s);
to:
b.A::myMethod(s);
then it works OK. However this is bulls*t of course, because later
if someone implements B::myMethod(const string& s) const, the
purpose of virtual method will be defeated.
How to cope with this??!
Thanks!
STF