Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If a private virtual function is overridden as a public function in the derived class, what are the problems?

using namespace std;
#include <cstdio>
#include <iostream>

class One{
    private:
        virtual void func(){
            cout<<"bark!"<<endl;
        }
};

class Two: public One{
    public:
        void func(){
            cout<<"two!"<<endl;
        }
};

int main(){
    One *o = new Two();
    o->func();
}

Why is there an error on o->func()?

I don't know the mechanism behind it... In my opinion, o->func() should call the func() in the derived class, which is public, so there wouldn't be problems, but it says:

 error: ‘virtual void One::func()’ is private
like image 791
lily Avatar asked Dec 01 '22 12:12

lily


2 Answers

Accessibility check is performed based on the static type of the object. The type of o is One*. This means that if One::func() is private, then o->func() won't compile.

On the other hand, which virtual member function will be called (i.e. dynamic dispatch) happens at run-time, based on the dynamic type of the object. So if One::func() is public, o->func() will call Two::func(), because o is pointing to an object of type Two.

For your sample code and use case, making One::func() private is just meaningless. But note that there's a famous idiom called Non-Virtual Interface, which makes use of private virtual member functions of base class.


Other suggestions:

  1. Don't forget to delete o;
  2. Add a virtual destructor in the base class One. Otherwise delete o; will lead to undefined behavior; e.g. the destructor of Two might not be invoked.

    class One {
        public:
            virtual ~One() {}
        // ...
    };
    
like image 163
songyuanyao Avatar answered Dec 04 '22 01:12

songyuanyao


A subclass can't ease inheritance restriction, even though func is virtual, it is still the inheritance restrictions remain.

please see this answer for compliated view of inheritance restrictions :

Difference between private, public, and protected inheritance

like image 28
Ran Koretzki Avatar answered Dec 04 '22 00:12

Ran Koretzki