Block virtual inheritance

Is there a way in modern C ++ to prevent a class from being actually inherited while providing regular inheritance? It seems impossible to me now, but in this language there were too many things that seemed impossible.

+6
source share
1 answer

The purpose of the virtual keyword specified for an inherited database is to prevent it from appearing in multiple instances in the inheritance hierarchy. Therefore, the use of this cannot prevent in the first place (see also "What is a virtual base class" ). I believe that you may have confused what your ability to control is what you can actually override by inheriting classes.

If you do not have virtual methods declared in your class, the inheritance class cannot provide any virtual overrides for any methods from this base.
It's best to put it semantically in the first place.

 class Foo { public: Foo() {} protected: ~Foo() {} // Explicitly non virtual destructor, prevents virtual inheritance // 'protected' forces inheritance to use this class }; 

Even using clean abstract interfaces introduced, this should work well.

 struct IFace { virtual void some_operation() = 0; virtual ~IFace() {} }; class Foo : public IFace { public: // Implementation of interface methods virtual void some_operation() { } // Same as above. Possibility of virtual inheritance stops here }; 

UPDATE:
It seems that the @ DieterLücking comment and your online code example refute what I said. Obviously, this does not stop using the virtual for inheritance in 1st place, and it seems that you can do nothing against it.

Although you can prohibit class inheritance for (re) implementing interfaces simply by providing these implementations as private, then:

 class Foo : public IFace { private: // Implementation of interface methods virtual void some_operation() { } }; 
+6
source

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


All Articles