0

I have been given the following lines of code

class Complex{
   private:
      double re, im;

   public: 
      Complex (double Re=0, double Im=0): re(Re), im(Im) {}

   double real() { return re; }
   double imag() {return im; }
};

My question pertains to the constructor (of whose purpose I'm still not quite sure)

I'm used to writing the constructor as:

Complex (double Re = 0, double Im = 0): {Re = re, Im = im;} 

rather than:

Complex (double Re=0, double Im=0): re(Re), im(Im) {}

Are the two lines of code equivalent, and specifically what does re(Re) and im(Im) do?

RN92
  • 1,380
  • 1
  • 13
  • 32
user9078057
  • 271
  • 1
  • 10
  • 2
    Possible duplicate of [What is this weird colon-member (" : ") syntax in the constructor?](https://stackoverflow.com/questions/1711990/what-is-this-weird-colon-member-syntax-in-the-constructor), in particular [this answer](https://stackoverflow.com/a/8523361/7976805) – Yksisarvinen Feb 18 '19 at 22:46
  • `Re = re, Im = im;` Didn't you mean `re = Re, im = Im;`? The way you wrote it, it doesn't assign to class member variables, leaving them uninitialized. – Algirdas Preidžius Feb 18 '19 at 22:56
  • @AlgirdasPreidžius I am also confused by the fact that we set `double Re=0` and `double Im=0`, does this not mean that, as you wrote, if `re = Re` and `im=Im` then for any complex number `z` in the main function, `z.re=0` and `z.im=0` irrespective of the value of `z`, since we have set `Re=0, Im=0` in the constructor? – user9078057 Feb 18 '19 at 23:03
  • 1
    @user9078057 I am sorry, but, what? 1) `Re`, and `Im`, are not the same as `re`, and `im` class members. `Re = re, Im = im;` tries to assign the values stored in `re`, and `im` (which contain indeterminate values), to `Re`, and `Im`, effectively not changing `re`, and `im` class members. 2) You referenced `main` function in your comment, but your [mcve], doesn't contain `main` function, so I don't even know what you are referencing. 3) You wouldn't even be allowed to do `z.re=0` and `z.im=0` from within `main`, due to the fact, that both `re`, and `im`, are `private`. – Algirdas Preidžius Feb 18 '19 at 23:07
  • On top of what Algirdas said, you **do not** set *anything* with this syntax: `Complex (double Re=0, double Im=0){}`. This is syntax for default arguments, meaning you can write `Complex c;` somewhere in your code and it will call constructor as if you wrote `Complex c {0, 0};` or `Complex c = Complex(0, 0)`. – Yksisarvinen Feb 19 '19 at 00:17

0 Answers0