Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

      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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading