0

I have a class 'Entity'. It has a user-defined constructor (implicit) with one argument as shown below.

class Entity
{
public:
    Entity(int a)
    {
        std::cout << a << std::endl;
    }
    Entity(const std::string& s)
    {
        std::cout << s << std::endl;
    }
};

int main()
{
    Entity e1 = (10, 20);
    Entity e2 = (10, 20, 30);
    Entity e3 = (10, 20, 30, 40);
    Entity e4 = (std::string("Hello"), std::string("World"));
    return 0;
}

The output of the above program is

20  
30  
40  
World

Can anyone tell me why only the last value (integer, string) passed is printed?

Note: If the constructor is made explicit, then there will be compilation error. Why this output with implicit constructor?

pkthapa
  • 1,029
  • 1
  • 17
  • 27
  • What precisely is e.g. `Entity e1 = (10, 20);` supposed to do? – 2b-t Apr 25 '21 at 17:17
  • `int i = (1, 2, 3, 4);` would assign `i = 4` the last value. `int i = (get_val(), get_val1());` here `i` is assigned returned value of `get_val1()` but first `get_val()` is evaluated, then `get_val1()`. I'm certain I read this in one of the SO answers but not able to find that answer now. Or search for comma operator. – Ch3steR Apr 25 '21 at 17:18
  • 2
    I have to admit, in all my years of working with C++ and with assisting developers/students who misunderstood C++ code, this is the first time I have ever seen round brackets misused this way to trigger this error. It's such a narrow and unlikely mistake to make since it requires implicit single-argument constructors and a misunderstanding of brace initialization. This basically works the way it does by a series of accidents revolving around the round-brackets and the comma operator -- but _you shouldn't be doing this_. – Human-Compiler Apr 25 '21 at 17:21

0 Answers0