hassle with operator overloading

++ operator
--------------1-----------------
void operator ++ (){
this->num = (* this).num + 1; //calling object is incremented by 1
}
--------------2-----------------
int operator ++ (){
return ((* this).num + 1); //returned copy of calling object incremented by 1
}
--------------------------------
which version is correct 1, 2 or both ??? and why???

-------------------------------------------------------------
= operator
--------------1-------------
void operator = (type obj){
* this = obj; //calling object is updated to copy of obj
}
--------------2-------------
type operator = (type obj){
return obj; //calling object receives a copy of obj and can update itself according to instructions in copy constructor
}
--------------------------------
which version is correct and why???
Last edited on
In both cases: Neither. All versions are wrong.

++ postfix operator should return a copy
++ prefix operator should return a reference to itself
= operator should return a reference to itself

That allows for things like the below without demanding unnecessary object copies:

1
2
3
bar = ++foo;
bar = foo++;
bar = foo = baz;


Proper overloads would be:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
type operator ++ (int)  // postfix
{
    type copy(*this);
    ++num;
    return copy;
}

type& operator ++ () // prefix
{
    ++num;
    return *this;
}

type& operator = (const type& rhs)
{
    num = rhs.num;
    return *this;
}
++ postfix operator should return a copy
++ prefix operator should return a reference to itself
= operator should return a reference to itself

what's the logic behind these restrictions ???
what's the logic behind these restrictions ???


That allows for things like the below without demanding unnecessary object copies:

...
Topic archived. No new replies allowed.