Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

prefix and postfix operators c++

class compl{
    float re,im;

public:
    compl(float r, float i)
        {re=r; im=i;}
    compl& operator++()
        {++re; return*this;} //(1)
    compl operator++(int k){
        compl z=*this; re++; im+=k; return z;} //(2)
    friend compl& operator--(compl& z)
        {--z.re; return z;}
    friend compl operator--(compl& z,int k)
        {compl x=z; z.re--; z.im-=k; return x;}
};

(1) Why do we have to return current object by reference? As I understood, reference is just a second name for something.

(2) Why do we have to save current object in z, then change the object and return the unchanged z? Doing this, we are returning the value that is not increased. Is it because of the way that postfix operator works(it returns the old value, and then increases it)

like image 300
Kioko Key Avatar asked Nov 22 '22 19:11

Kioko Key


1 Answers

(1) You don't have to, but it's idiomatic because it allows for chaining operators or calls.

(2) Yes, postfix should return the previous value.

like image 174
Luchian Grigore Avatar answered Jan 10 '23 21:01

Luchian Grigore