开发者

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

开发者 https://www.devze.com 2023-04-09 07:29 出处:网络
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.

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 vo开发者_StackOverflow社区id 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.


Inspirel lets you define your own rules: http://www.inspirel.com/vera/


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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号