Jeff
Jeff

Reputation: 3525

private overrides of private methods pattern? (ANSWER: NVI)

What's the accepted jargon (if any) for describing methods meant to be invoked only virtually and from other methods in the base? I've occasionally seen this referred to as a callback, but that seems to stray pretty far from the original definition of that term. I'm not even sure that this merits being called a pattern, but I'm trying to become more precise in commenting my code. Thanks for the help!

// Abstract class.
class A {
public:
  void run() { while (call()) { /* ... */ } }
private:
  virtual bool call() = 0;
};

// Completion/specialization of A.
class B : public A {
private:
  // Standard term to indicate this pattern?
  bool call();
};

Summary: This appears to be called the Non-Virtual Interface pattern, a special case of the Template Method Pattern. Thanks to Nick and Steven for the help!

Upvotes: 1

Views: 246

Answers (4)

Nick Meyer
Nick Meyer

Reputation: 40272

This is sometimes called the "non-virtual interface" (or NVI) pattern. It is often used when the implementation for the virtual function needs to vary between derived classes, but the base class needs control over when the function is called.

For example, the base class could make another function call before or after the virtual call instead of making the virtual function public and relying on overrides to call the base implementation themselves (and at the right time!)

Upvotes: 3

Pontus Gagge
Pontus Gagge

Reputation: 17258

Um... private virtuals? Why invent new terminology? It's a language construct, not an idiom, and to my mind not interesting enough to be termed a pattern.

Upvotes: 0

sbi
sbi

Reputation: 224079

I've heard the pattern where you don't have any virtual functions in your interface as the Non-Virtual Interface pattern, NVI for short.

In other contexts it's referred to as the Template Method pattern, where your run() is a template method, with derived classes jumping in to fill in the gaps.

Upvotes: 1

Steven Sudit
Steven Sudit

Reputation: 19620

Could be a template method pattern.

Upvotes: 5

Related Questions