Search code examples
c++c++11static-analysiscppcheck

How to make cppcheck 2.5 show error on calls to a virtual function in constructor. Older version shows this error


In the list of cppcheck rules there is

<error id="virtualCallInConstructor" severity="style" msg="Virtual function 'f' is called from constructor '' at line

  1. Dynamic binding is not used." verbose="Virtual function 'f' is called from constructor '' at line 1. Dynamic binding is not used."/>

I've written a call to a virtual functions in several classes in my solution and run cppcheck o them, but it didn't show this error.

I've used GUI and also run cppcheck from command line with --enable=style and --enable=all

How can I make cppcheck to show this issue? I'm using latest cppcheck

Another dummy code I've run cppcheck on

class A
{
public:
    A() { }
    virtual void fin() = 0;
};

class B : public A
{
public:
    B() { fin(); }
    void fin() { std::cout << "l"; }
};

class C : public B
{
public:
    C() {}
    void fin() { std::cout << "c"; }
};

UPDATE: I've checked cppcheck 1.8 and it shows me this errors. What's happened to the 2.5 that it didn't show them despite in the set of rules of 2.5 it is stated that it should find such?


Solution

  • I found this comment https://sourceforge.net/p/cppcheck/discussion/general/thread/b18f7aaf/#d726

    It will be fixed in the next release. For now I have disabled the check. But it can be enabled again if we write such warnings properly. The checker must ensure that the class is a base class!

    The post relates to 1.84

    Looking at the code it is still disabled: https://github.com/danmar/cppcheck/blob/6397e29f84de53655904326ef1ca892a509275c5/lib/checkclass.h

    // FIXME: Only report warnings for inherited classes
    // checkClass.checkVirtualFunctionCallInConstructor();