Ensuring the virtuality of third-party methods

I am extending the class provided by the third part library. The class, let's call it Foo , has a reset() method that can be called to restart the behavior of Foo . The reset() method is also used inside the class.

 class Foo { public: void reset () { /* ... */ } void something () { reset(); } }; 

So far, I needed to overload the reset() method to reset add my extra functions:

 class Bar : public Foo { public: void reset() { /* ...something... */ Foo::reset(); } }; 

Unfortunately, since the Foo::reset() method is not virtual, by calling Bar::something() , I call the Foo::reset() method instead of Bar::reset() .

Is there a way (other than overloading Foo::something() ) to make it back-virtual?

+7
c ++ virtual
source share
5 answers

You cannot extend classes that are not intended to be extended.

+5
source share

You cannot make reset() virtual in your library so that it affects the base class without changing the base class code. To begin with, the compiler did not add the necessary accounting code, which allows it to make reset() virtual calls.

+3
source share

There is no “clean path” for this using inheritance. Virtual is the difference in compilation / link time: using vtable to resolve the method at runtime (virtual) and direct binding (not virtual).

+2
source share

No, It is Immpossible. The virtuality of a method is determined when the method is declared, and you cannot change it later in the base class.

To let you do this, it will be nothing more than a disaster. Virtual methods simply behave differently than non-virtual methods, and this must be taken into account when designing an object. With this suggestion, I would have to think that all my methods can behave differently. This significantly increases the cost of developing the application and reduces reliability.

+1
source share

If neither reset nor something virtual, you are screwed, and this is the end of the story. If something is virtual, you can override it. However, if these necessary methods are not virtual, then the class is not intended to be extended (or implemented correctly if it was intended).

Edit:

MAY try to try the composition, for example

 class Bar { Foo f; // foo methods, etc, wrapped here void something() { f.reset(); reset(); } }; 

But if you need a whole, implicit transformation, thing, you are still full.

+1
source share

All Articles