TICS Coding Standard Viewer 
TIOBE Software Quality Framework
Print-friendly version
©TIOBE Software www.tiobe.com
 
C++ Coding Standard
Search

Rule:  INT#026Checked automatically with code checker

Synopsis:In a derived class, if you need to override one of a set of the base class's overloaded virtual member functions, then you must override the whole set, or use using-declarations to bring all of the functions in the base class into the scope of the derived class
Language:C++
Severity Level:2
Category:Class Interface


Description:

Rationale: The overload set can be hidded both by overRIDING or by overLOADING part of the overload set in a derived class. Examples:

// OVERLOAD

// Incorrect
class Base
{
   public:
      void doSomething(char c);
};

class Derived : public Base
{
   public:
      void doSomething(int i);
}

int main()
{
   char c = 'a';
   int i = 100;
   Derived d;

   d.doSomething(i);    // will call Derived::doSomething(int)
   d.doSomething(c);    // will unexpectedly call Derived::doSomething(int)
}

// Correct
class Base
{
   public:
      void doSomething(char c);
};

class Derived : public Base
{
   public:
      using Base::doSomething; // Exposes Base::doSomething(char)
      void doSomething(int i);
};

int main()
{
   char c = 'a';
   int i = 100;
   Derived d;

   d.doSomething(i);    // will call Derived::doSomething(int)
   d.doSomething(c);    // will call Base::doSomething(char)
}




// OVERRIDE

// INCORRECT
class Base
{
   public:
      virtual int doSomething(int i);
      virtual double doSomething(double d);
};

class Derived : public Base
{
   public:
      int doSomething(int i) override;
};

int main()
{
    int i = 2;
    double dbl = 2.3;
    Derived d;

    d.doSomething(i);  // will call derived::doSomething(int)
    d.doSomething(dbl) // will unexpectedly call derived::doSomething(int)
}


// CORRECT
class Base
{
   public:
      virtual int doSomething(int i);
      virtual double doSomething(double d);
};

class Derived: public Base
{
   public:
      using Base::doSomething; // Exposes doSomething(double)
      int doSomething(int i) override;
};

int main()
{
    int i = 2;
    double dbl = 2.3;
    Derived d;

    d.doSomething(i);  // will call derived::doSomething(int)
    d.doSomething(dbl) // will call derived::doSomething(double)
}


Literature References:
C++ Core Guidelines C.138
Stroustrup 15.2.2