0

Code:

#include <iostream>

class Foo{
        int t;
    public:
        Foo(int t=0):t(t){}
        void show(){
            std::cout << t;
        }
};

void Func(Foo foo){
    foo.show();
}

int main(){
    Func(0);
    return 0;
}

Output: 0

So apparently when I pass an integer to a function that's supposed to take a Foo type argument, it somehow converts it to Foo(and even takes the integer as a constructor parameter) and works fine. I guess it has something to do with the way constructor works, but I really don't understand why it works that way. I researched a lot but couldn't find anything about it. Any thoughts?

emso-c
  • 3
  • 1
  • 3
  • 2
    See [Converting constructor](https://en.cppreference.com/w/cpp/language/converting_constructor). – François Andrieux Nov 26 '20 at 21:54
  • 1
    Because you have a suitable constructor, the compiler can implicitly convert any `int` value to a `Foo` object. So the call becomes, essentially, `Func(Foo(0))`. If you want to prohibit such conversions you need to mark the constructor as `explicit`. – Some programmer dude Nov 26 '20 at 21:57
  • While the proposed duplicate is not phrased as a match to yours, the accepted answer to the proposed duplicate could be copy-pasted as an answer to yours. – JaMiT Nov 26 '20 at 22:04

0 Answers0