Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Complex C++ class

  1. Oct 31, 2005 #1

    Has anyone here used the complex C++ class before Header <complex>? I am trying to do something VERY straightforward but there doesnt seem to be any way to do it!

    Basically, I define a complex, and then want to re-asign its real and imaginary parts:

    complex<double> A(1,1); // assign real and im parts to 1.

    //Now I want to change the real and imaginary parts to 2, 2

    A.real() = 2; //error

    //The only way I can make it work is

    A = complex<double> (2,2);

    //but I am guessing that this is much less efficient because you are basically recalling the complex constructor followed by the assignment operator!

    Does anyone know how to do this? It seems silly that you can not access the real and imaginary parts of the class via a function of the form

    double& complex<double>::real();

  2. jcsd
  3. Oct 31, 2005 #2
    A.real() and its counterpart for the imaginary portion should be private rather than public attributes. There should be a set and get method, or "+", "-", "/" and "*" should be overridden so you can add another complex number to it.
  4. Oct 31, 2005 #3


    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    To quote Microsoft's documentation:

    This template function cannot be used to modify the real part of the complex number. To change the real part, a new complex number must be assigned the component value.

    Now, to allay your fears about efficiency, if the implementation and compiler are any good, the expression:

    a = complex<int>(5, imag(a));

    should be just as efficient as if you could write

    real(a) = 5;

  5. Nov 2, 2005 #4


    User Avatar

    Such a class is called an immutable class. They can be useful in certain circumstances and may help the compiler with optimisation.
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook