0
class Numbers{
int a;
public :
Numbers(){};
Numbers(Numbers &obj) 

why cant we do something like this ?

Numbers(Numbers) / Numbers(Numbers obj)

why we always have to use reference object/variabele?

  • Well, classes often do provide copy and/or move constructors, but otherwise constructors may have arguments of any kind and amount. – user7860670 Apr 24 '21 at 19:49
  • 4
    Numbers(Numbers &obj) is the copy constructor. If you call Numbers(Numbers) instead, it passes Numbers by value. Which calls the copy constructor, which is passed by value which calls the copy constructor, rinse and repeat. – Offtkp Apr 24 '21 at 19:49
  • `Numbers(Numbers obj)` -- Have you tried to [compile something like this](http://coliru.stacked-crooked.com/a/8583f0dabd7a35f5)? – PaulMcKenzie Apr 24 '21 at 19:50
  • To think of it, in order to properly call such constructor, you would need to copy the argument into the stack, which would require to once again call that same constructor, and we got ourselves a stack overflow. Of course, copy elision would probably prevent that, but it's an interesting thought regardless – IWonderWhatThisAPIDoes Apr 24 '21 at 19:51
  • @PaulMcKenzie i did its throwing error –  Apr 24 '21 at 19:53
  • @Offtkp Numbers(Numbers) is not compiling –  Apr 24 '21 at 19:54
  • 2
    @Spartex Yes you can't compile that. My comment is trying to help you understand why it wouldn't make sense for that to compile. – Offtkp Apr 24 '21 at 19:56
  • @IWonderWhatThisAPIDoes i didnt get what you said can you elaborate in simple language ? –  Apr 24 '21 at 19:57
  • 1
    @Spartex -- Do you know what happens if you pass a parameter by value? A copy is made. What function is involved in making copies? The copy constructor. So how is it possible to create a copy constructor if what you're passing will call the copy constructor, which will call the copy constructor, which will call the copy constructor, etc. etc. – PaulMcKenzie Apr 24 '21 at 20:00
  • @Spartex do you understand what recursion is? Passing a parameter *by value* requires making a *copy* of the value being passed. So, if a copy constructor took its parameter *by value*, you would get into an endless loop, trying to make a copy by calling the copy constructor, which would need to make a copy by calling the constructor, which... over and over forever (well, at least until the call stack runs out of memory). – Remy Lebeau Apr 24 '21 at 20:01

0 Answers0