Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

question regarding "this" pointer in c++

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?.

like image 692
silent Avatar asked Mar 28 '10 06:03

silent


People also ask

What is the purpose of this pointer?

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.

Can this pointer point to another class?

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.

Does pointer save memory space?

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 of the following is are types of this pointer?

Which among the following is/are type(s) of this pointer? Explanation: The this pointer can be declared const or volatile.


1 Answers

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;
like image 92
codaddict Avatar answered Sep 20 '22 15:09

codaddict