2

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.

Amirreza A.
  • 736
  • 4
  • 10
  • 1
    A relevant piece of the accepted answer at the duplicate: "While direct initialization has all constructors available to call, and _in addition_ can do any implicit conversion it needs to match up argument types, copy initialization can just set up one implicit conversion sequence." – aschepler Jun 24 '21 at 14:12
  • 2
    Expanding on that: An implicit conversion sequence can have at most one user-defined conversion. The conversion from `const char*` to `std::string` is user-defined, and so is the conversion from `std::string` to `BigNum`. – Nathan Pierson Jun 24 '21 at 14:15
  • The literal answer to the question in the title is "because the code doesn't have any casts". The term here should be "convert". A cast is something you write in your code to tell the compiler to do a conversion. – Pete Becker Jun 24 '21 at 14:20
  • @PeteBecker Isn't what you're saying the same as implicit casting? – Amirreza A. Jun 24 '21 at 14:23
  • @AmirrezaA. -- there is no such thing as an implicit cast. A cast is something **you write in your source code** to tell the compiler to do a conversion. You're talking about an **implicit conversion**. – Pete Becker Jun 24 '21 at 16:50

0 Answers0