Search code examples
c++overridingvirtual

How to be warned when overriding a virtual method with wrong visibility


When overriding a virtual method, I noticed that when I make a mistake in the visibility (protected method overridden as a public method), I'm not warned by the compiler.

It is valid C++, but usually it is a mistake.

For example:

#include <iostream>

class Base
{
protected:
  virtual void ProtectedMethod(void)
  {
    std::cout << "Base::ProtectedMethod" << std::endl;
  }
};

class Derived : public Base
{
public:
  virtual void ProtectedMethod(void)
  {
    std::cout << "Derived::ProtectedMethod" << std::endl;
  }
};

int main(int, char* [])
{
  Derived d;
  d.ProtectedMethod();
}

I tried compiling with gcc and clang, with -Wall -Wextra, with no luck. I ran CppCheck on this code, still no luck.

What tool can help me detect this ? I need to fix the whole sources of a library I'm working on.


Solution

  • I found a solution to my needs using ctags.

    CTags can parse C++ and dump information to a file.

    Using the following options:

    $CTAGS -f $TAGFILE --fields=fkstia --c++-kinds=+p  -R $SOURCES
    

    I can get all the needed information in an easily parseable format.

    Piping $TAGFILE through a few grep commands, I can verify that a known function name has the expected visibility, and issue a warning with the incriminated file otherwise.

    Here is a bash snippet to extract info from the ctags output :

    #!/bin/bash
    function check_method {
        echo "Checking $1 (should be $2 and is not)"
        cat $TAGFILE | grep "^$1    " | grep "access" | grep -v "access:$2" | cut -f 2
        echo
    }
    
    # will warn anytime a method called ProtectedMethod is not protected
    check_method ProtectedMethod protected