Alphas Supremum
Alphas Supremum

Reputation: 505

how to handle wrong value passing to constructor parameters?

I have my class Stack

class Stack
{
public:
    Stack(unsigned int Size)
   {
    size = Size;
   }

private:
    unsigned int size;
    void* Block;
};

int _tmain(int argc, _TCHAR* argv[])
{
    Stack x(-1);
    return 0;
}

I want to make sure that even I pass negative value to the constructor argument that the object wont be constructed , but when I'm giving -1 value , it's accepting it and the variable size value is 4294967295 , which is the same -1 after removing the sing bit as far as I know ...

so how I shall handle this situation ? shall I throw exception ? or just make to take default value in case of wrong value ?

Upvotes: 3

Views: 779

Answers (2)

Mr.C64
Mr.C64

Reputation: 42944

If you are using the Visual C++ compiler (MSVC), as a general rule, you may want to compile your code at /W4 (i.e. warning level 4), so the compiler speaks up more frequently, and helps identifying programmer's mistakes.

For example:

C:\Temp\CppTests>cl /EHsc /W4 /nologo test.cpp

warning C4245: 'argument' : conversion from 'int' to 'unsigned int',
signed/unsigned mismatch

EDIT

In addition, you may want to mark your constructor explicit, to avoid implicit bogus conversions from integers to instances of your Stack class.

Upvotes: 1

Brian Cain
Brian Cain

Reputation: 14619

I want to make sure that even I pass negative value to the constructor argument that the object wont be constructed

One way to do this is -Wsign-conversion -Werror

$ clang++ -Werror -Wsign-conversion -c stack.cpp
stack.cpp:18:13: error: implicit conversion changes signedness: 'int' to 'unsigned int' [-Werror,-Wsign-conversion]
    Stack x(-1);
          ~ ^~
1 error generated.


$ cat stack.cpp

class Stack
{
    public:
        Stack(unsigned int Size)
        {
            size = Size;
        }

    private:
        unsigned int size;
        void* Block;
};

typedef const char _TCHAR;
int _tmain(int argc, _TCHAR* argv[])
{
    Stack x(-1);
    return 0;
}

Upvotes: 0

Related Questions