0
class test{
 public:
 explicit test(){}
};

int main(){
 test t1;
 test t2(t1);
 
 return 0;
}

Why is the above snippet compiling? the constructor test() does not take any inputs, it's even coded as such explicitly. However test t2(t1); seems to compile?

Edit

Is the auto generated constructor there to support casts such as this?

class test{
 public:
 test(int in){}
 // test(test& in){}
};

void call(test in){} 

int main(){
 test t1(5);
 call(test(t1)); 

 return 0;
}

test(t1) is technically a cast which could call the class constructor.

Dan
  • 2,694
  • 1
  • 6
  • 19
  • 3
    `test` has a implicitly-generated [copy constructor](https://en.cppreference.com/w/cpp/language/copy_constructor) taking `test`. – songyuanyao Jul 17 '21 at 03:31
  • 1
    tl;dr of dupe: declaring a constructor other than the copy or move constructor does not suppress the auto-generated copy constructor. – Joseph Sible-Reinstate Monica Jul 17 '21 at 03:33
  • @songyuanyao is the input `t1` simply ignored? ie `t2` doesn't become `t1`? – Dan Jul 17 '21 at 03:34
  • @Dan Ignored? No, `t2` is copied from `t1`. – songyuanyao Jul 17 '21 at 03:39
  • @songyuanyao I see, I added an edit, is it to support the cast I mentioned? creating a constructor myself causes compilation errors. – Dan Jul 17 '21 at 03:42
  • @Dan Temporary can't be bound to reference to non-const. Try changing your copy constructor to take `const test&`. – songyuanyao Jul 17 '21 at 03:46
  • @songyuanyao Correct, but is the reason for having a copy constructor generated by default to support such cases? if the compiler didn't do so `test(t1)` would have failed. – Dan Jul 17 '21 at 03:47
  • @Dan Sorry I can't get your question, the implicitly-generated copy constructor takes `const Test&`. – songyuanyao Jul 17 '21 at 03:55
  • @songyuanyao let me rephrase. If the compiler didn't create a copy constructor then `test(t1)` would have failed. `test(t1)` is a simply cast, which is a basic functionality of the language so Im guessing the copy constructor is there to support this behaviour (plus more of course). – Dan Jul 17 '21 at 03:57
  • And as the last question I like to ask, in my first example `t2` is a copy of `t1` but resides on a different memory address right? – Dan Jul 17 '21 at 03:58
  • 1
    @Dan I'm not sure about the rationale but yes, `test` has a implcitly-generated copy constructor. But note that copy constructor is not generated for all the cases (see the duplicate). And yes, `t1` and `t2` are two independent objects. – songyuanyao Jul 17 '21 at 04:11

0 Answers0