Menu

Possibly false negative with class that has no constructor

T Tanner
2022-07-05
2022-07-06
  • T Tanner

    T Tanner - 2022-07-05

    For this code:

    class X
    {
      int a;
      int b;
    
      public:
      void init() { a = b = 1; }
    
    };
    
    class Y
    {
      X x;
      public:
      Y() {}
    };
    

    (which I admit is somewhat dubious), you get this

    $ cppcheck --enable=warning test.cc
    Checking test.cc ...
    test.cc:48:3: warning: Member variable 'Y::x' is not initialized in the constructor. [uninitMemberVar]
      Y() {}
      ^
    

    Now I know that X doesn't have a constructor, and it should. However until it DOES have a constructor, I have no way of initialising the member variable concerned, and I don't think you should warn about it.

    I freely admit it is shocking bad that it doesn't have a constructor - the init() method is used to initialise it and that sets up everything fine. But I don't want to fiddle too much with code I don't really understand properly while introducing people to the joys of cppcheck. And cppcheck does provide a warning about classes with no constructors, so that whole thing can be dealt with then.

    So I feel this is a bit of a false positive.

    Thank you for listening.

     
  • T Tanner

    T Tanner - 2022-07-05

    and sorry for mistyping the title!

     
  • Daniel Marjamäki

    Did you forget to call x.init(); ?

     

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.