Menu

duplInheritedMember for name hiding

2025-02-14
2025-02-20
  • Nikita Leontiev

    Nikita Leontiev - 2025-02-14

    Code:

    #include <string>
    #include <sstream>
    
    class Base
    {
    protected:
        int num;
    public:
        void setter(int param)
        {
            num = param;
        }
        int getter()
        {
            return num;
        }
    };
    
    class Derived: public Base
    {
    public:
        void setter(std::string param)
        {
            num = atoi(param.c_str());
        }
        std::string getter()
        {
            std::stringstream ss;
            ss << num;
            return ss.str();
        }
    };
    

    Name hiding is used for both setter and getter.
    cppcheck 2.16.0 output:

    test\main.cpp:26:14: warning: The class 'Derived' defines member function with name 'getter' also defined in its parent class 'Base'. [duplInheritedMember]
     std::string getter()
                 ^
    test\main.cpp:13:6: note: Parent function 'Base::getter'
     int getter()
         ^
    test\main.cpp:26:14: note: Derived function 'Derived::getter'
     std::string getter()
                 ^
    

    duplInheritedMember here looks like false positive, because getter is not a duplicate method.
    It's not clear why this warning is not generated for setter method for which name hiding is also applied.
    If name hiding is bad practice, then there should be appropriate warning.

     
  • CHR

    CHR - 2025-02-14

    The two setter functions have incompatible argument lists, which suppresses the warning.

     
  • Nikita Leontiev

    Nikita Leontiev - 2025-02-19

    Yes, I understand that setter methods have different signatures, that's why warning is not generated. If cppcheck has no questions for setter method, then current case it's obviously a false positive, because both setter and getter are about name hiding.

     
  • CHR

    CHR - 2025-02-20

    getter() without args is ambiguous, setter(x) can be resolved by the argument type.

     

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.