-1

I want to build a class that throws an exception if the parameter list is of the wrong type,

For example this class: in the header

class rectangle
{
public:
    rectangle(int, int);
    int getarea();
private:
    int length;
    int width;

};

in cpp

rectangle::rectangle(int l, int w)
{
    if (l!=int|| w!=int)
        throw string("Exception found!");
    length=l;
    width=w;        
}

I want the constructor to throw an exception if it is called in the following ways in the main program:

rectangle rec1(3.5, 4);
rectangle rec1(a, 5);

because 3.5 and a are not of type int. How can I check if the argument of the constructor is of the desired type?

Dave
  • 43
  • 2

2 Answers2

2

I want to build a class that throws an exception if the parameter list is of the wrong type,

You probably don't want that because then it would be too late to do anything about it.

For strings (and most other types) the program won't even compile but for float, double, char, short, long and long long (and their unsigned versions) there are built-in conversions to int and if you want to make sure that your program won't even compile unless ints are used, you could make a template out of your constructor:

#include <type_traits>

class rectangle {
public:
    template<typename T, typename U = std::enable_if_t<std::is_same_v<int, T>, T>>
    rectangle(T l, T w) : length(l), width(w) {}

    int getarea() const { return length * width; }

private:
    int length;
    int width;
};
Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
  • ... but the linked duplicate solves it so much more elegantly. I'll leave my answer up as an alternative but for your specific problem I think the linked dup serves you better. – Ted Lyngmo Aug 04 '19 at 21:31
0

In c/c++ if you have a method with an

int

parameter then the value of this parameter will definitely be a natural number between

-2,147,483,648 and 2,147,483,647 

on x86 and x64 architecture.

It will never be a float, a string, false or something else.

You might want to check if it is < 0 as it is a length in your example.

You could also change it to

unsigned int

Then the variable will be between

0 and 4,294,967,295
zomega
  • 1,538
  • 8
  • 26