C++ private and protected virtual method

后端 未结 3 1372

It seems that it is good to make the virtual methods private in order to separate the interfaces for following two clients - 1. clients that instantiate an object and call the

3条回答
  •  别那么骄傲
    2021-02-08 22:56

    You are exactly right:

    • NVI (Non-Virtual Interface) requires that virtual methods not be public
    • Calling the base class method requires that it not private

    therefore protected is the obvious solution, at least in C++03. Unfortunately it means you have to trust the derived class developer not to forget to call "super".


    In C++11, you can use final to prevent a derived class from overriding a virtual method; it means though that you are forced to introduce a new hook, example:

    class Base {
    public:
        void save() {
            // do something
            this->saveImpl();
            // do something
        }
    private:
        virtual void saveImpl() {}
    };
    
    class Child: public Base {
    private:
         virtual void saveImpl() final {
             // do something
             this->saveImpl2();
             // do something
         }
         virtual void saveImpl2() {}
    };
    

    Of course, there is the trouble of having to come up with a new name each and every time... but at least you are guaranteed that Child::saveImpl will be called because none of its children can override it.

提交回复
热议问题