Consider:
#include <iostream>
using namespace std;
struct A {
virtual void f() { cout << "A::f" << endl; }
virtual void f() const { cout << "A::f const" << endl; }
};
struct B : public A {};
struct C : public A {
virtual void f() { cout << "C::f" << endl; }
};
int main()
{
const B b;
b.f(); // prints "A::f const"
const C c;
c.f();
// Compile-time error: passing ‘const C’ as ‘this’ argument of
// ‘virtual void C::f()’ discards qualifiers
}
(I'm using GCC.)
So it seems that the const version of f() gets hidden in C. This makes a lot of sense to me, but is it mandated by the standard?
f
virtually (through a base class pointer or reference) here. All lookups off
find the most derivedf
. – Embusvirtual
, butconst
is what the whole question is about. Overridingf()
hidesf() const
. – Slovenia