Why is it allowed to call derived class' private virtual method via pointer of base class?

前端 未结 6 1651
难免孤独
难免孤独 2020-12-15 07:35
# include 
using namespace std;

class A
{
    public:
    virtual void f()
    {
        cout << \"A::f()\" << endl;
    }
};
class B:pu         


        
6条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-15 07:55

    This code is allowed because f is public in A's interface. A derived class cannot change the interface of a base class. (Overriding a virtual method isn't changing the interface, nor is hiding members of a base, though both can appear to do so.) If a derived class could change a base's interface, it would violate the "is a" relationship.

    If the designers of A want to make f inaccessible, then it should be marked protected or private.

提交回复
热议问题