Reputation: 67
In the code below, I don't get what "this" is (not the keyword, but what it points to). Is "this" is reference or pointer to current object?
And when checking a=a assign if(this!=&a)
, why "this" is compared with &a, and not with a?
The class Book have private member *num_pages
that points to number of pages in the book.
Book &Book::operator=(const Book& a){
if(this!=&a){
delete num_pages;
num_pages = new int;
*num_pages = *a.num_pages;
}
return *this;
}
Upvotes: 0
Views: 70
Reputation: 726579
In the example above this
is a pointer to the object on the left hand side of the assignment operator. For example, if you write the code below
Book b1, b2;
b1 = b2;
then inside your operator =
this
is the address of b1
, and a
is b2
.
why
this
is compared with&a
, and not witha
?
Because this
represents a pointer to Book
, while a
represents a constant reference to Book
. In order to compare the two, their level of indirection must be the same (both must be pointers). This is done so that a valid self-assignment
b1 = b1;
would not cause problems.
Upvotes: 3
Reputation: 18556
this is a pointer. It is compared with the address of a to avoid self-assignment.
Upvotes: 1