C++ private and protected virtual method

后端 未结 3 1366

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:42

    It's difficult to tell what you're asking, but from the example, you do not need to make the method protected. It actually can be private. For details about the subtleties see this post: What is the point of a private pure virtual function?.

    So long as you're not calling the private member from derived class (or outside classes), you're ok. Overriding of private members is ok. It does sound quite naughty and wrong that you can override your parent's privates, but in c++ you're allowed to do this.

    The following should be ok:

    #include 
    using namespace std;
    
    class A {
    
        string data;    
    
    private:
    
        virtual void SaveData()= 0;
    
    public:
    
        A():data("Data of A"){}
    
        void Save(){
            cout << data << endl;        
            SaveData();
        }
    };
    
    class B : public A {
    
        string data;
    
    private:
    
        virtual void SaveData() { cout << data << endl;}
    
    public:
    
        B():data("Data of B") {}
    
    };
    

提交回复
热议问题