Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nonvirtual interface idiom for more than two levels of inheritance?

The non-virtual interface idiom describes how the virtual methods are nonpublic customisation points, and public methods are nonvirtual to allow the base class to control at all times how the customisation points are called.

This is an elegant idiom and I like to use it, but how does it work if the derived class is a base class in itself

like image 599
andreas buykx Avatar asked Sep 22 '08 21:09

andreas buykx


2 Answers

It works, because the derived class can override a private virtual function of a base class, even if the base class function overrides its base class function.

This is perfectly legal:


class Parent
{
public:
  int foo() {return bar();} // the non-virtual public interface
private
  virtual int bar();
};

class Child : public Parent
{
private:
  virtual int bar();  // overrides Parent::bar()
};

class Grandchild : public Child
{
private:
  virtual int bar(); // overrides Child::bar();
};
like image 95
Dima Avatar answered Nov 19 '22 12:11

Dima


The derived class can decide for itself:

You can just override the method completely by implementing the virtual function. You can augment the method by calling the 'middle' classes function at some point in your derived class method.

If that's not what you want, you need to set it up explicitly in the 'middle' class. I wouldn't though. If you find yourself desiring this, it probably means you didn't give the base class enough customization points.

like image 30
Mike Elkins Avatar answered Nov 19 '22 14:11

Mike Elkins