0

Say I create a class Complex with members rand phi that writes complex numbers in polar form through the constructor

Complex (double Re=0, double Im=0) : r(sqrt(Re*Re + Im*Im)), phi(atan2(Im,Re)) {}

In the class I find component functions like

double real() const {return r*cos(phi);}

which seem logical, but I do not understand the neccessity of const (is there a difference between const double real() and double real() const?)

I have been told that it is important such that the component function does not modify the class.

Modify in what sense? Surely no members of the class will be added or removed because of a component function, and how would constactually avert this? Any help is greatly appreciated.

user9078057
  • 187
  • 1
  • 6
  • Spend some time reading up on [const correctness](https://isocpp.org/wiki/faq/const-correctness). – Fred Larson Mar 12 '19 at 19:54
  • 2
    "is there a difference between const double real() and double real() const" - Yes. In the first case `const` applies to the return value (and is quite pointless) in the second it applies to the `this` pointer of the object the function is invoked on (not pointless). – Jesper Juhl Mar 12 '19 at 19:55
  • 1
    Modify in the sense that `double real() const { r = 1; return r*cos(phi);}` will result in a compiler error while `double real() { r = 1; return r*cos(phi);}` will not. As a rule of thumb you can make methods `const` by default and only if they need to modify the object remove the `const` – 463035818_is_not_an_ai Mar 12 '19 at 20:05

0 Answers0