0

I'm currently learning c++ and in inheritance. I have an issue concerning use of const. Here's the code :

#include <iostream>
using namespace std;

class Base {
     public : 
      virtual void pol()  const
     {
        cout<< " Base ";
     }
};

 class Derived : virtual public Base {
    public:
       void  pol( ) 
    {
        cout<< "derived";
    }
};

int main( )
{
    const Base *b = new Derived();
    b-> pol();
    return 0;
}

My teacher absolutely wants me to use "const Base *b" in the function main()

When I compile and execute this code the result printed is "Base" , while I'm expecting getting an "derived". I know it come from the " const" use in :

      virtual void pol()  const

But it's for the moment the only way I found to get this compile. Thanks for your time

  • 2
    What exactly is your question? Is there a reason one `pol()` function is `const` while the other `pol()` is **not** `const` and therefore not overriding the base function? – Drew Dormann Nov 09 '22 at 19:43
  • 2
    If you'd used the [override](https://en.cppreference.com/w/cpp/language/override) or [final](https://en.cppreference.com/w/cpp/language/final) specifier, you'd have gotten a compiler error indicating what's wrong here. `Derived::pol` doesn't override `Base::pol`, it shadows it. The lack of `const` on `Derived::pol` means it has a different signature, so it gets treated as a different function. – Nathan Pierson Nov 09 '22 at 19:43
  • Since `poll()` is `const` and doesn't mutate the object, it makes sense to obtain a `const` pointer to it. Btw; mark the overriding `poll` with `override` and then mark it `const` as well - derived functions don't automatically inherit `const` they are different functions without the `const`. – Jesper Juhl Nov 09 '22 at 19:44
  • 2
    Btw; [Why is "using namespace std;" considered bad practice?](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) – Jesper Juhl Nov 09 '22 at 19:49

1 Answers1

2

The problem is that in the derived class const-ness for method pol is missing and therefore is considered a different method, not an override.

Add const there too and it will work as you expect

6502
  • 112,025
  • 15
  • 165
  • 265