[C++] Overriding interface methods

Started by
6 comments, last by Zahlman 14 years, 1 month ago
I am using a technique I picked up off CodeProject where virtual methods are not necessary to write an interface. However, there are a select few routines I leave virtual and invite the user to override. A factory method isn't enough to make derived methods available, at least, not on first glance. Since I cannot derive in the manner I'm accustomed to, how can I override methods in an interface properly as a client?
Advertisement
This is an interface:
struct IFoo {  virtual ~IFoo() {};  virtual void foo() = 0;};struct MyFoo : public IFoo {  virtual void foo() {    //  }};

Even if there is some hack, I really wouldn't try to break C++ even more by messing around with it.

Implementor of the interface must implement all interface functions. This is consistent in other languages as well.


There is also a concept of abstract base class:
struct AbstractFoo {  virtual ~IFoo() {};  virtual void foo() {} // empty body};

When extending this interface it is not necessary to override any functions.
Quote:Even if there is some hack, I really wouldn't try to break C++ even more by messing around with it.


What was the danger with the approach shown here? (See "Improved with no Virtual Methods") I saw that approach in FMOD, even.
That's not a technique designed for multiple derived classes. You have one implementation and that's it.
Quote:Original post by zyrolasting

What was the danger with the approach shown here? (See "Improved with no Virtual Methods") I saw that approach in FMOD, even.


It took me a while trying to figure out what it all has to do with polymorphism.

The technique is about reducing dependencies in header files by pushing as much as possible into implementation, but without overhead associated with PIMPL. It reduces compilation times.

It is not really an interface, there will always be one and exactly one single concrete class, the interface exists only for the sake of build system.
Well, at the end of the day I'm going to need to hide all of the uglier details of my object definition, but there are choice high-level methods I need to keep virtual. I wouldn't want to ask the user to override all methods of the class due to it's size, and I cannot compartmentalize as the the methods are event driven and are in need of the object. I take it there's no easy way out, eh?
Then use pimpl in your base class.
One of my great revelations from a few years back is that pImpl is actually basically designed specifically to support polymorphism. The pImpl sets up a pointer in order to indirect and hide implementation, and calling virtual functionality requires having a pointer or reference rather than a value (since then the type is known at compile-time). As it happens, you can reuse the same layer of indirection for both goals (compile-time "data hiding" and run-time polymorphism).

This topic is closed to new replies.

Advertisement