C++ Inheritance and use of Const

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

>Solution :

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

Leave a Reply