Trying to learn C++ and hitting a wall with a few things. Would appreciate some pointers from the C++ experts on explaining on what is happen ing under the hood.
My BigNum class is below. My questions are
BigNum b1 = BigNum(2, {2, 8});does not workError: No matching constructor for initialization of 'BigNum'- But
int arr[] = {2, 8}; BigNum b1 = BigNum(2, arr);works
- But
- I also see some compiler warnings for all constructors below. E.g:
Candidate constructor not viable: requires 0 arguments, but 2 were providedfor the default constructor below - Is there a one-line way to initialize the private members in the constructor. E.g:
BigNum(int numDigits, int digits[]): _n(numDigits), _digits(digits) {};- Or even better
BigNum(int numDigits = 0, int digits[] = {}): _n(numDigits), _digits(digits) {};
class BigNum {
int _n = 0;
int _digits[MAX_DIGITS] = {};
public:
BigNum() {};
BigNum(int numDigits, int digits[]) {
if (numDigits >= MAX_DIGITS || numDigits < 0) {
return;
}
_n = numDigits;
memcpy(_digits, digits, _n * sizeof(_digits[0]));
};
BigNum(const BigNum &bigNum) {
_n = bigNum._n;
memcpy(_digits, bigNum._digits, _n * sizeof(_digits[0]));
};
};
std::initializer_list. With such a constructor, you could doBigNum({2, 8})2. Those are not separate warnings, but further explanations for the original error. The compiler tells you what constructors it tried, and why each one was found unsuitable.std::arrayorstd::vector. These can be initialized in the constructor initializer list, while plain array cannot.std::initializer_listwork if data member is anint array. Seems to only work forstd::vectorstd::initializer_listfor the param and using for loop to initialize _digits works. Can you make this the answer, so that I can accept?