Receive instant 1:1 support from technology experts, using our real-time conversation and whiteboard interface. Your first 5 minutes are always free.

Solved

Posted on 1998-11-01

I have a inline function that is to allow for function chaining. using an add function that is already written.

this is what I have so far.

fraction & inc(){*this=add(*this,*this);return *this;}

the function inc() is supposed to add 1 to the instance.

Thank you for any help.

this is what I have so far.

fraction & inc(){*this=add(*this,*thi

the function inc() is supposed to add 1 to the instance.

Thank you for any help.

2 Comments

First I assume you have a way of converting a constant number to a 'fraction' object. E.g., via a constructor.

There are two possible cases:

(1) Let's assume add() is written like this:

fraction add(const fraction& a, const fraction& b)

{

fraction result;

// Do something...

return result;

}

Note that add returns BY VALUE and not BY REFERENCE. That is because it creates a new object instead of modifying an existing one. Therefore, inc() should not be implemented in terms of add().

Now, consider the other case:

(2) Let's assume add() is written like this:

fraction& add(fraction& obj, const fraction& x)

{

// Do something...

return obj;

}

In this case, I assume modifies the first argument (and also returns the result BY REFERENCE, since no new object is created). If that is the case, inc() could be written like this:

fraction& inc(const fraction& obj)

{

return add(obj, 1);

}

However, if inc() and add() modify the object, it will be much better to implement them as member functions:

fraction& fraction::add(const fraction& x)

{

// Do something to add x to *this...

return *this;

}

fraction& fraction::inc()

{

return add(1);

}

But if that's the case, why not use operators?

fraction& fraction::operator+=(const

{

// Do something to add x to *this...

return *this;

}

fraction& fraction::operator++(int) // postfix increment

{

return operator+=(1);

}

Now you can write:

fraction x, y;

// ...

x += y;

++x;

Hope it helps.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Title | # Comments | Views | Activity |
---|---|---|---|

returning a dereferenced pts in C++ | 10 | 149 | |

C language IDE – Compilers installation | 14 | 71 | |

operator overload: incompatible type and too many params | 5 | 77 | |

c++ using a LPCOLESTR * and adding a string varaible to the Pointer | 2 | 58 |

Join the community of 500,000 technology professionals and ask your questions.