Are there precedents for private public-virtual methods?

#include <iostream> struct A { virtual void foo(){ std::cout << "A"; }; }; struct B : public A { private: void foo() override { std::cout << "B"; } }; int main() { A *p = new B; p->foo(); // prints B // B b; // b.foo(); // error: foo is private return 0; } // g++ -std=c++11 -Wall -Wextra -Wpedantic main.cpp && ./a.out 

Thus, we can call B.foo() polymorphically, but not directly. Are there any use cases when someone wants to use this functionality?

+6
source share
2 answers

It depends on the design of the base class. Suppose you have a base class

 class Stream { public: virtual bool canSeek() = 0; virtual void seek(int offset) = 0; }; 

Note. This example comes from the .NET world, where the Stream class library class does have such a CanSeek virtual property. I do not want to discuss whether this is a good design, as I can see valid arguments for both sides. It is enough that such base classes exist in reality.

Now the derived class can indicate that

 class SpecificStream final : Stream { private: virtual bool canSeek() { return false; } virtual void seek(int offset) { throw "no seek for you"; } } 

In this derived class, the fact that seek implemented in general is that it is technically necessary. However, any code that deals with this SpecificStream already knows that the seek function is completely useless with this class and should not be called. When encoding with the Stream base class, it may make sense to check the result of canSeek() and call seek only if the result was true. When coding with the SpecificStream class, it makes no sense to check canSeek() , since its result is statically known, and it definitely does not make sense to call seek() . If such calls are a programmer error, it makes sense to help the compiler provide useful messages for such calls.

+5
source

This prevents you from invoking a method that is not polymorphic, that's all: using the scope resolution operator to directly access the method can lead to complex code maintenance. In an environment where you know that not all are experienced developers (perhaps scientific programmers who contribute to creating a large code base), it’s worth introducing templates to protect your code from them!

However, Java explicitly prohibits this, as they consider it to be bad.

+2
source

Source: https://habr.com/ru/post/1012377/


All Articles