I am implementing a BigNumber class in C++. Here is the code:
main.cpp:
int main()
{
BigNum a("50");
BigNum b = "1";
std::cout << a + b << std::endl;
}
BigNum.hpp:
class BigNum
{
private:
std::string number;
public:
BigNum();
BigNum(const std::string &s);
BigNum operator+(const BigNum &other);
BigNum operator*(const BigNum &other);
BigNum operator=(const std::string &s);
friend std::ostream &operator<<(std::ostream &os, const BigNum &n);
};
I have removed some of the parts to keep it concise. The code stores the number in a std::string and overloads operators to do mathematical operations.
In line 4 of main.cpp
, I'm assuming that the BigNum(const std::string &s)
constructor of BigNum
is called (not the overloaded assignment operator since I'm creating a new object), just like line 3. But surprisingly I get a compiler error.
.\main.cpp: In function 'int main()':
.\main.cpp:8:16: error: conversion from 'const char [2]' to non-scalar type 'BigNum' requested
8 | BigNum b = "1";
| ^~~
When I change BigNum b = "1";
to BigNum b = std::string("1");
, it works fine. Why isn't "1" being casted from a character array to a std::string implicitly? Cuz it happens when passing arguments to functions. Is it mentioned in the C++ standard? I'm new to C++ so I would appreciate it if you elaborate.
Edit:
My question is different from this question, where the difference between different syntaxes of constructing and copying an object is discussed. I'm actually getting an error and asking why isn't the character array being casted implicitly. Please at least read the question before marking it as a duplicate.