i have been given class with int variables x and y in private, and an operator overload function,
class Bag{
private:
int x;
int y;
public:
Bag();
~Bag();
//.......
//.....etc
};
Bag operator+ (Bag new) const{
Bag result(*this); //what does this mean?
result.x += new.x;
result.y += new.y;
}
What is the effect of having "Bag result(*this);" there?.
The this pointer is a pointer accessible only within the nonstatic member functions of a class , struct , or union type. It points to the object for which the member function is called. Static member functions don't have a this pointer.
It is true that a pointer of one class can point to other class, but classes must be a base and derived class, then it is possible.
Features of Pointers:Pointers save memory space. Execution time with pointers is faster because data are manipulated with the address, that is, direct access to memory location. Memory is accessed efficiently with the pointers. The pointer assigns and releases the memory as well.
Which among the following is/are type(s) of this pointer? Explanation: The this pointer can be declared const or volatile.
Bag result(*this)
creates a copy of the object on which the operator function was called.
Example if there was:
sum = op1 + op2;
then result
will be a copy of op1
.
Since the operator+
function is doing a sum of its operands and returning the sum, we need a way to access the operand op1 which is done through the this
pointer.
Alternatively we could have done:
Bag result;
result.x = (*this).x + newobj.x; // note you are using new which is a keyword.
result.y = (*this).y + newobj.y; // can also do this->y instead
return result;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With