0

Hello I have a simple question: If I have a class that has a constructor that takes an integer for example then if I copy-initialize an object of that class then is copy-constructor or constructor is called:

class M 
{
    public:
        M(int) { cout << "M(int)\n"; }
        M(const M&) = delete;
        M(const M&&) = delete;
};


int main()
{

    M m = 9; // why M(int) is called but not a copy-ctor or move-ctor?
}
  • AS you can see I have an ambiguity here: M m = 9; I think it is a form of Copy-initialization so normally I think the copy-ctor or move-ctor should be called. I've declared theme deleted to get an compile-time error but it works?
Maestro
  • 2,512
  • 9
  • 24
  • 3
    `M m = 9;` is just a different syntax for `M m{9};` (or any of the other 9001 initialization syntaxes in C++). Try `M n {1}; M m = n;`. This will invoke the copy-constructor. – n314159 Dec 07 '19 at 22:59
  • 1
    If you want to avoid such implicit conversion, mark your constructor as `explicit` – Rhathin Dec 07 '19 at 23:16
  • Rules where adjusted at some points by the standard committee. Not sure about the reason. Before that, compiler were allowed to optimize away the constructor if the code would have compile. – Phil1970 Dec 08 '19 at 00:04
  • @n314159: But why this code works on C++20 but not on C++14 and C++11? – Maestro Dec 08 '19 at 11:17
  • @Maestro All code I posted should work from C++11 onward. If you have a problem you should be more specific. – n314159 Dec 08 '19 at 12:22

0 Answers0