-1

Hi I wrote a casting function from myClass to int and vise versa therefore I made one of the functions as explicit. When doing so I got an error.

The functions:

    CircularInt(int n): CircularInt(1, 12 , n) { }
    explicit operator int() const{ return current;};

Error on:

CircularInt hour {1, 10 , 7 };   // current = 7
int i = hour;

Error:

error: cannot convert ‘CircularInt’ to ‘int’ in initialization int i = hour;

When erasing the "explicit" all is good, Why is this?

p.s.

May I mention that I was unable to find a question exactly like this, I found many questions of people that forgot to do explicit, asking what is explicit (didn't find something in those exact question them for me) etc.

Probably this is from not understanding completely understanding explicit...

Tomer
  • 531
  • 7
  • 19
  • I don't understand this question. If you read up on what `explicit` does, as you claimed, then why exactly are you confused by this behavior? – Baum mit Augen Apr 29 '18 at 11:10
  • 1
    then first make sure what `explicit convert` means. – con ko Apr 29 '18 at 11:14
  • @BaummitAugen sorry for the misunderstanding in my question, I rephrased it. My problem was that I thought I already understood what explicit does and the praticular stackoverflow questions that I read I was unable to conclude something for my problem due to my false misconception of what explicit does. – Tomer Apr 29 '18 at 11:22

1 Answers1

2

When erasing the "explicit" all is good, Why is this?

Because this is what explicit is supposed to do: allow for conversion if written explicitely, i.e. int i = static_cast<int>(hour);.

Jodocus
  • 7,493
  • 1
  • 29
  • 45