0

According to http://www.cplusplus.com/reference/complex/complex/complex/, class complex<double> has a default construct of the form complex (double re = 0.0, double im = 0.0);. However, I don't know if this is really correct. Could anyone explain the strange behavior of the code below?

#include <iostream>
#include <complex>
#include <typeinfo>
using namespace std;

int main() {

    complex<double> cmp1(1, 2);
    complex<double> cmp2(1); //isn't the same as cmp2(1, 0.0) ?
    complex<double> cmp3(); //isn't the same as cmp3(0.0, 0.0) ?

    cout << cmp1.real() << "\n"; //=> 1
    cout << cmp1.imag() << "\n"; //=> 2

    cout << cmp2.real() << "\n"; //=> 1
    cout << cmp2.imag() << "\n"; //=> 0

    //cout << cmp3.real() << "\n"; //error (why?) //mark1
    //cout << cmp3.imag() << "\n"; //error (why?)

    /* error message output by `mark1`: */
    /* request for member ‘real’ in ‘cmp3’, which is of */
    /* non-class type ‘std::complex<double>()’ */

    cout << cmp3 << "\n"; //=> 1 (why?)

    cout << typeid(cmp1).name() << "\n"; //=> St7complexIdE
    cout << typeid(cmp2).name() << "\n"; //=> St7complexIdE
    cout << typeid(cmp3).name() << "\n"; //=> FSt7complexIdEvE

}

Environment:

$ g++ --version
g++ (Ubuntu 5.4.0-6ubuntu1~16.04.9) 5.4.0 20160609

Compiling option:

$ g++ -Wall -std=c++98 <file name>
M.M
  • 138,810
  • 21
  • 208
  • 365
ynn
  • 3,386
  • 2
  • 19
  • 42
  • 1
    Most vexing parse? --> [Nope.](https://stackoverflow.com/questions/1424510/most-vexing-parse-why-doesnt-a-a-work#comment22220864_1424510) – user202729 Mar 21 '18 at 11:18
  • This is a function declaration. Search "vexing parse". – llllllllll Mar 21 '18 at 11:18
  • Congratulations, you are now a MVP – M.M Mar 21 '18 at 11:19
  • `complex cmp3();` declares a function called `cmp3` taking no parameters and returning a `complex`. – Matteo Italia Mar 21 '18 at 11:19
  • 1
    `complex cmp3();` is a declaration of a function named `cmp3()` that accepts no arguments and returns a `complex`. Remove the `()` if you want to declare a variable of type `complex`. – Peter Mar 21 '18 at 11:20
  • It looks like that -- every time a duplicate question is asked again, its canonical duplicate gets upvoted once more. – user202729 Mar 21 '18 at 11:23

1 Answers1

0

change:

complex<double> cmp3(); //isn't the same as cmp3(0.0, 0.0) ?

to

complex<double> cmp3; //isn't the same as cmp3(0.0, 0.0) ?

and it should work just fine

It happends because compiler may assume that that is a function declaration

Ch1v1
  • 121
  • 1
  • 7