Click to See Complete Forum and Search --> : what is the difference between reference and pointer
wenjiahe
May 1st, 2003, 08:07 AM
hi, buddy!I am a beginer here. thanks for your answer:
bow to everyone.
I am always confused by the reference and pointer. in the
code below I think it should return the Pointer 'this' but why
it return '*this', i think *this means the contents of the pointer.
who can help me? thanks a lot!
const Array &Array::operator =(const Array &right)
{
if(&right!=this)
{
delete [] ptr;
size = right.size;
ptr=new int[size];
assert(ptr!=0);
for(int i =0; i<size;i++)
ptr[i] = right.ptr[i];
}
return *this;
}
this function should return a const reference of Array,right?
kuphryn
May 1st, 2003, 08:51 AM
Correct.
The overloaded operator returns a constant reference to an object, thus allowing code:
Object A;
Object B = A;
The overloaded operator can in theory return a pointer to the object, but that does not work with the code above.
Change this line:
if(right!=*this)
{}
Kuphryn
wenjiahe
May 1st, 2003, 09:17 AM
Originally posted by kuphryn
Correct.
The overloaded operator returns a constant reference to an object, thus allowing code:
Object A;
Object B = A;
The overloaded operator can in theory return a pointer to the object, but that does not work with the code above.
Change this line:
if(right!=*this)
{}
Kuphryn
thanks for you reply.
i think if(&right!=this) and if(right!=*this) will have the same effect. the code i paste above is a sample code of a book.i
have tested it. it's correct code. what i want to know is why
not return this but return *this.
Andreas Masur
May 1st, 2003, 09:19 AM
Originally posted by wenjiahe
what i want to know is why
not return this but return *this.
Because 'this' is a pointer to the object and '*this' is the actual object. Since the operator will return a reference to the object and not the pointer you have to return the latter one...
wenjiahe
May 1st, 2003, 09:26 AM
Originally posted by Andreas Masur
Because 'this' is a pointer to the object and '*this' is the actual object. Since the operator will return a reference to the object and not the pointer you have to return the latter one...
ok, you mean reference to an object equal the object itself,right?
Andreas Masur
May 1st, 2003, 09:34 AM
Originally posted by wenjiahe
ok, you mean reference to an object equal the object itself,right?
Correct...a reference can be seen as a transparent way of looking to the object itself...
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.