0

Apologies in advance for this question. It's been awhile since I've used C++ and I can't seem to find an exact tutorial that answers my question. I think this is an example of implicit conversion, but I'm not sure.

Code:

class Square
{
public:        
    Square(int size) : size{size}
    {
    }

    int getSize() const
    {
        return size;   
    }

private:
    int size;
};

void doSomething(Square square)
{
    cout << "doSomething called with " << square.getSize() << endl;   
}

int main()
{
    // Should be passing in a Square type here, but instead passing an int.
    doSomething(23);
    return 0;
}

Output:

doSomething called with 23

Questions:

  1. Is this an example of implicit conversion?
  2. How is this occurring? I'd be satisfied with a link that explains this in more detail. For what it's worth, I've already gone over the cplusplus.com explanation of Type conversions.

Thank you!

broAhmed
  • 192
  • 1
  • 2
  • 16
  • 1
    Make the constructor of `Square` [explicit](https://en.cppreference.com/w/cpp/language/explicit) and you will disallow the implicit conversion. – Paul Rooney Nov 09 '18 at 02:00
  • Thanks! I was trying to understand why the conversion was occurring, but great to also learn a way to prevent it. – broAhmed Nov 09 '18 at 02:30

1 Answers1

1

In brief: because Square square = 23; would be valid, the call doSomething(23) matches the signature doSomething(Square square) ; that's how candidate function selection in overload resolution works.

If there were other overloads of doSomething that also matched the call, then the overloads would be ranked based on which conversions were required for each one.

The code Square square = 23; is valid because Square has a converting constructor.

M.M
  • 138,810
  • 21
  • 208
  • 365