0

I have the following code that is part of an exercise (about which I asked here).

class MyInt
{
public:
   MyInt(int x) : MyValue(new int(x)){};

   MyInt()
   {
     MyValue = 0;
   }
private:
  int* MyValue;
}

int main(int argc,char** argv)
{ 
   MyInt y(1);
   MyInt x(y);
   .... //Mode code
}

The code compiles and runs (if I didn't forget to put a relevant part of it here). I would like to understand the line

MyInt x(y);

I don't have a constructor that inputs a MyInt, only one that doesn't have parameters and another that inputs an int. The MyInt doesn't have a definition of operator().

What is the computer doing in that line?

Community
  • 1
  • 1
Kae
  • 279
  • 2
  • 10
  • 1
    It is calling your `copy constructor` which the compiler made for you. – Cory Kramer Jul 21 '14 at 22:14
  • Oh! It is a syntax I didn't know, then. So, x(y), depending on the context and types of x and y can mean: (1) constructor of x with argument y, or (2) operator() of object x with argument y, or (3) copy constructor which puts the data of y in x. This last I didn't know about. – Kae Jul 21 '14 at 22:34
  • 1
    "Constructor of `x` with an argument of `y`" (where `x` and `y` are of the same type) is, by definition, a copy constructor. – Igor Tandetnik Jul 21 '14 at 22:36
  • 1
    @Karene They're not the same syntax, even if they look similar. `MyInt x(y);` is a declaration. It's all one thing, so you shouldn't look at the `x(y)` separately. It creates an object by calling a particular constructor. It never invokes `operator()`. On the other hand, `x(y)` as part of an expression means invoking `operator()` on the object `x`. – Joseph Mansfield Jul 21 '14 at 22:37

1 Answers1

0

That is the copy constructor executed for MyInt x(y) generated by C++ for you. If you don't define a copy constructor C++ generates one for you. Check copy constructor section in here.

Cahit Gungor
  • 1,477
  • 23
  • 30