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?
const is part of the signature, and leaving it off changes the signature, and thus hides the method rather than overrides it. "
No, because virtual void func() is not an override for virtual void func() const .
A virtual function is a member function in the base class that we expect to redefine in derived classes. Basically, a virtual function is used in the base class in order to ensure that the function is overridden. This especially applies to cases where a pointer of base class points to an object of a derived class.
I will (once more) link this great article :
First, [the compiler] looks in the immediate scope, in this case the scope of class C, and makes a list of all functions it can find that are named f (regardless of whether they're accessible or even take the right number of parameters). Only if it doesn't does it then continue "outward" into the next enclosing scope [...]
So yes, the const
version of f
is hidden, and that's perfectly normal. As pointed out by Simone, you can use a using
statement to bring A::f
in C
scope.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With