zq****@gmail.com wrote:
class String
{
public:
String& operator=(const String& str);
private:
char* pdata;
}
String& String::operator=(const String& str)
{
if(this==&str)
return;
delete[] pdata;
pdata=new char[strlen(str.pdata)+1];
if(pdata==0)
return;
strcpy(pdata,str.pdata);
return *this;
}
str.pdata seem to be invalid,but the compiler(VC 6.0) dosen't report
errors.Why the object pointed by this pointer can access the
object's(referrenced by str) member pdata.Whether we can do like that
in specific functions(copy constructor...?).
Who can give me an answer? Thanks in advance.
Yes, this is allowed. It's not so strange when you think of it: the
class itself has access to itself. You can't break anything here,
because the only code that can access the private members is code that
belongs to the class anyway. Any member function can access private
members of any other object that has it's _exact_ type. It doesn't work,
for example, if you try to access protected attributes of a base class
of String in this way.
--
Regards,
Ferdi Smit (M.Sc.)
Email:
Fe********@cwi.nl
Room: C0.07 Phone: 4229
INS3 Visualization and 3D Interfaces
CWI Amsterdam, The Netherlands