user11308549
user11308549

Reputation:

What is the difference between ClassName objectName(4); and ClassName objectName = 4;


    class Pizza() {
        private:
            int value;
        public:
            Pizza(int x) {
                value = x;
            }
    }

    int main() {

        // What is the difference here under the hood?
        Pizza p1 = 2;
        Pizza p2(2);
    }

The reason I ask this is that if I have a Pizza constructor that takes a string,


    Pizza p3 = "letters here";
    Pizza p4("letters here");

The line with p3 produces a type conversion error. This is because the actual type it is looking to take is const char*.

The line with p4 works fine. Why is it that when "letters here" is in ( ), it is made a string object, but when "letters here" just comes after the = sign, it's type is const char*.

Upvotes: 0

Views: 182

Answers (2)

Silvio Mayolo
Silvio Mayolo

Reputation: 70297

I'm going to assume you have a constructor that looks like this.

Pizza(std::string x) {
  ...
}

And you're calling it like this.

Pizza p3 = "letters here";
Pizza p4("letters here");
Pizza p5 = Pizza("letters here");

p4 and p5 are fine. We call the Pizza constructor with a const char* argument. We need an std::string, and there's a handy implicit conversion from const char* to std::string, so it all works. p3 is different; we're trying to convert a const char* to a Pizza. We have a conversion from const char* to std::string and one from std::string to Pizza, but the C++ compiler will only do one implicit conversion per argument, so it won't take those two hops we need to get there.

There are two ways around the problem, if you still like the p3 syntax.

  1. We could write a constructor that takes a const char*, which would require only one implicit conversion so everything would check out. The constructor could even delegate to the std::string version, if we want the same behavior.
  2. We could explicitly cast to std::string, as Pizza p3 = std::string("letters here");. Again, this only requires one implicit conversion, so the compiler would accept it.

Upvotes: 3

MFH
MFH

Reputation: 1734

Confusingly for newcomers, both syntaxes in your string-example are calls to the same constructor!

Pizza p3 = "letters here"; //the same as Pizza p3("letters here");  !!!
Pizza p4("letters here");

Upvotes: -1

Related Questions