mardi 2 avril 2019

Why private method overwrites base class public virtual method(with public inheritance)?

Example code

#include <iostream>

class A 
{
    public :
     A() {}
     virtual void F() { std::cout << "A::f";}
};

class B: public A
{
    public:
     B() {}


    private:
      void F()  { std::cout << "B::f"; }
};

int main()
{
    B b;
    A * ptr = &b;
    ptr->F();
    return 0;
}

Method F() from class B overrides A::F() despite fact it's in private section not public. Why I cannot have private method B::F() which doesn't overrides A::F() ?

If virtuals works without checking private/public sections, maybe there should be any warning or error thrown?

Aucun commentaire:

Enregistrer un commentaire