Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ override private pure virtual method as public

Why does this happen?

http://coliru.stacked-crooked.com/a/e1376beff0c157a1

class Base{
private:
    virtual void do_run() = 0;
public:
    void run(){
        do_run();
    }
};

class A : public Base {
public:
    // uplift ??
    virtual void do_run() override {}
};


int main()
{
    A a;
    a.do_run();
}

Why can I override a PRIVATE virtual method as public?

like image 438
tower120 Avatar asked Jun 06 '18 14:06

tower120


People also ask

Can you override private virtual methods?

This means that private functions are visible but not accessible. A private virtual function can be overridden by derived classes, but can only be called from within the base class.

Can we override pure virtual function?

Yes !! It improves code clarity: override keyword prevents ambiguity and convey it's meaning of overriding its base class method.

Can we override private method in CPP?

Users can improperly override private virtuals just as easily as public ones- they're defining new classes after all. If the public shouldn't modify a given API, don't make it virtual AT ALL in publicly accessible objects. If t may help, C++11 has 'final' keyword to prevent further overrides.

Can pure virtual functions be private?

A virtual function can be private as C++ has access control, but not visibility control. As mentioned virtual functions can be overridden by the derived class but under all circumstances will only be called within the base class. Example: C++


2 Answers

According to https://en.cppreference.com/w/cpp/language/virtual#In_detail overriding a base's virtual member function only care about the function name, parameters, const/volatile-ness and ref qualifier. It doesn't care about return type, access modifier or other things you might expect it to care about.

The linked reference also specifically notes that :

Base::vf does not need to be visible (can be declared private, or inherited using private inheritance) to be overridden.

Nothing that I can find explicitly gives permission to do this, but the rules of overriding do not prevent it. It's allowed by virtue of virtual functions and function overriding existing and not disallowing this case.

If you are asking why this is how the language is, you may have to ask the standardization committee.

like image 63
François Andrieux Avatar answered Oct 02 '22 13:10

François Andrieux


That behavior is intended. If a method is virtual then it's meant to be customizable by derived classes, regardless of access modifier.

See here

like image 34
rawberry Avatar answered Oct 02 '22 14:10

rawberry