Let Wallet be a class that represents the amount of coins and bills in a purse. The class has
got a data element amount of type long. The binary operator += shall be overloaded as an
inline method. Identify the error in the following definition.

Wallet& operator+=(Wallet& w)
{ // add the amount contained in another purse
Wallet* this;
this->amount += w.amount;
w.amount = 0L;
return *this;
}

Can somebody explain me this?

Dani AI

Generated

The compile error comes from trying to declare an identifier named "this" inside a member function. In C++ this is a built‑in keyword that already refers to a pointer to the current object, so you cannot redeclare or shadow it. Remove the attempted declaration and just use the implicit this pointer (or access members directly; this-> is optional inside the class). As suggested, compiling will show the exact diagnostic quickly.

Also check the function semantics. The operator should return a reference to the current object (so callers can chain assignments). Because the provided code sets the other wallet's amount to zero, passing the argument by non‑const reference is necessary if that mutation is intended. However, mutating the right‑hand operand is surprising for an operator+= in many designs; if the goal is a transfer, prefer a clearly named transfer method or, in modern C++, use move semantics to express ownership transfer.

For the language rules and canonical patterns, see the C++ reference on the implicit this pointer and on operator overloading; they explain why redeclaring this is illegal and how to implement member operators properly. This resolves the reported error without changing the intended arithmetic or transfer behaviour.

cppreference: this
cppreference: operator overloading

Recommended Answers

All 2 Replies

It's simple. This is a method of the Wallet class that takes a Wallet as a parameter, takes its amount of money and adds it to the Wallet on which the method is invoked (this). The other wallet has its amount set to 0.

To find the error, create the class with the minimum requirements and try to compile it! You will see the error, but it's not so difficult to see. Then, this homework question will be completed.

Yet another tip: the only correct statement is return *this; ;)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.