bliny
bliny

Reputation: 67

Overloading operator = in c++

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

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

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 with a?

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

kraskevich
kraskevich

Reputation: 18556

this is a pointer. It is compared with the address of a to avoid self-assignment.

Upvotes: 1

Related Questions