Menu

Non-explicit constructor test

Fraser
2018-08-05
2019-07-05
  • Fraser

    Fraser - 2018-08-05

    There is a test for not declaring a single argument constructor explicit but it does not consider constructors with default arguments that will also perform an implicit conversion. The example below will be different with explicit not commented out.

    class A {
    public:
    /explicit/ A(int const a1=0, int const a2=0) : a1_(a1), a2_(a2) {}
    ~A() {}
    private:
    int
    a1_,
    a2_;
    };

    int _tmain(int argc, _TCHAR* argv[])
    {
    short b(7);
    A a= b;
    return 0;
    }

     
  • Fraser

    Fraser - 2018-08-06

    The default argument for the first parameter is optional but necessary for all other parameters. I have changed the type of b to int to simplify the program code.

    class A {
    public:
    /explicit/ A(int const a1, int const a2=0) : a1_(a1), a2_(a2) {}
    ~A() {}
    private:
    int
    a1_,
    a2_;
    };

    int _tmain(int argc, _TCHAR* argv[])
    {
    int b(7);
    A a= b;
    return 0;
    }

     
  • Daniel Marjamäki

    This should be reported in Trac (http://trac.cppcheck.net) instead so we don't forget it.. do you have a Trac account?

     
  • Fraser

    Fraser - 2018-08-08

    Yes, you changed the password recently. I will report this one.

     
  • Fraser

    Fraser - 2019-07-05

    Its reported with number 8676. explicit now has meaning for constructors with other numbers of parameters since C++ 2011.

     

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.