How to prevent a derived class from publishing a private / protected virtual function?

There are good reasons for creating a base class interface with all virtual functions, both private and protected (see this ). But how can we prevent derived classes (which may be in the hands of external clients) from creating a private virtual function as public? In "Practically Yours" the authors talk about this problem, but the solution is not discussed.

Change . From your answers and, as I thought before, it seems that this is impossible to prevent. But since it is easy to make a mistake in this situation (the client necessarily touches on a protected virtual function), it would be reasonable that the compiler warned about this use. I tried to check it with g ++. First, I wrote:

class A {
        protected:
        virtual void none() { return; }
};

class B: public A {
        public:
        void none() { return; }
};

g++ -c -Wall -pedantic file.cppcompiled without errors. Adding -Weffc++gave a warning: warning: ‘class A’ has virtual functions and accessible non-virtual destructorthat makes sense. After adding a virtual destructor, there is no warning. Thus, there are no warnings regarding this simple case.

+5
source share
6 answers

, ++ , . - , , - .

- ++ , . , , , . , ++ - .

: "" - , . D & E , , 1:

. , : . , , ++ , . , default - - default . , . , , . C " ". , , , . (§2.10).

§ 2.2 , :

, , .

, , - , 20 ++ , - ( ) .

1 §4.3, . 115, 116.

+12

. "" - .

+2

++, , , . DRM, . A B, A B , , B.

, , , B. , , , , , . , ( ) . , , , , " ".

- make , , . , .

, , , .

+2

/ . - . .

+2

, .

? , .

++ . , , . , ( , ).

+2

, . , . , , RTTI .

protected:
class ProtectedToken { virtual ~ProtectedToken() { } };
virtual void my_tough_cookie(int arg,
  ProtectedToken const &tok = ProtectedToken() ) {
    assert ( typeid( tok ) == typeid( ProtectedToken ) );
}

Of course, this is not good to do with anyone, including yourself.

Edit: Bah, it doesn't work. Even if this happened, you could do public: using Base::ProtectedTokenand thus defeat the defense. Another 15 minutes of my life were gone ...

+1
source

All Articles