Calling overridden function from the overriding function

Igor Oks picture Igor Oks · May 13, 2009 · Viewed 18.9k times · Source

Suppose I have virtual function foo() in class B, and I need slightly different behavior in one of B's derived classes, class D. Is it OK to create an overriding function D::foo(), and call B::foo() from there, after the special case treatment? Like this:

void D::foo()
{
  if (/*something*/)
     // do something
  else
     B::foo();
}

I am not asking whether that would work, I know it will. I want to know, whether it is right in terms of a good OOD.

Answer

Gorpik picture Gorpik · May 13, 2009

This is perfectly good. In fact, the canonical way of performing some operations is calling the base class method, then do whatever (or the other way around). I am thinking of operator= here. Constructors usually work that way, too, even if this is a bit disguised in the initialization list.