Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does overriding a non-const virtual method hide a const overload?

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?

like image 999
Ari Avatar asked Nov 11 '10 09:11

Ari


People also ask

Can we override const method?

const is part of the signature, and leaving it off changes the signature, and thus hides the method rather than overrides it. "

Can a virtual function be const?

No, because virtual void func() is not an override for virtual void func() const .

What is virtual void in C++?

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.


1 Answers

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.

like image 198
icecrime Avatar answered Oct 09 '22 00:10

icecrime