public member function
<complex>

std::complex::complex

initialization (1)
complex (const T& re = T(), const T& im = T());
copy (2)
complex (const complex& x);
conversion (3)
template<class U>  complex (const complex<U>& x);
Complex number constructor
Constructs a complex object.

It may be constructed from two values (re and im) or from another complex.

The float, double and long double specializations only allow explicit conversions to types with lower precision. Their constructors are declared as:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
template<> class complex<float> {
  complex (float re = 0.0f, float im = 0.0f);
  explicit complex (const complex<double>& x);
  explicit complex (const complex<long double>& x);
  // ... (other members)
}
template<> class complex<double> {
  complex (double re = 0.0, double im = 0.0);
  complex (const complex<float>& x);
  explicit complex (const complex<long double>& x);
  // ... (other members)
}
template<> class complex<long double> {
  complex (long double re = 0.0L, long double im = 0.0L);
  complex (const complex<float>& x);
  complex (const complex<double>& x);
  // ... (other members)
}
The float, double and long double specializations have constexpr constructors and only allow explicit conversions to types with lower precision. Their constructors are declared as:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
template<> class complex<float> {
  constexpr complex (float re = 0.0f, float im = 0.0f);
  explicit constexpr complex (const complex<double>& x);
  explicit constexpr complex (const complex<long double>& x);
  // ... (other members)
}
template<> class complex<double> {
  constexpr complex (double re = 0.0, double im = 0.0);
  constexpr complex (const complex<float>& x);
  explicit constexpr complex (const complex<long double>& x);
  // ... (other members)
}
template<> class complex<long double> {
  constexpr complex (long double re = 0.0L, long double im = 0.0L);
  constexpr complex (const complex<float>& x);
  constexpr complex (const complex<double>& x);
  // ... (other members)
}

To construct a complex object from its polar form, see function polar.

Parameters

re, im
Real and imaginary parts, respectively, of the complex number.
T is complex's template parameter.
x
A complex object.
If constructed from a complex object with a different template parameter (U), the appropriate conversions are performed.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// complex constructor example
#include <iostream>     // std::cout
#include <complex>      // std::complex

int main ()
{
  std::complex<double> first (2.0,2.0);
  std::complex<double> second (first);
  std::complex<long double> third (second);

  std::cout << third << '\n';

  return 0;
}

Output:

(2,2)


Exception safety

Narrowing conversions on floating-point types may produce undefined behavior (when the value is too small or too great to be represented by the type). Otherwise, constructing a complex never throws exceptions.

See also