virtual function in private or protected inheritance

前端 未结 5 2208
予麋鹿
予麋鹿 2021-02-12 22:52

It\'s easy to understand the virtual function in public inheritance. So what\'s the point for virtual function in private or protected inheritance?

For example:

5条回答
  •  温柔的废话
    2021-02-12 22:53

    Private inheritance is just an implementation technique, not an is-a relationship, as Scott Meyers explains in Effective C++:

    class Timer {
    public:
        explicit Timer(int tickFrequency);
        virtual void onTick() const; // automatically called for each tick
        ...
    };
    
    class Widget: private Timer {
    private:
        virtual void onTick() const; // look at Widget private data
        ...
    };
    

    Widget clients shouldn't be able to call onTick on a Widget, because that's not part of the conceptual Widget interface.

提交回复
热议问题