}
in the above calss, why memeber function can access the object other's
private m_data?
according to Principle of Encapsulation ,a boject can not access other
object's private memeber.
do anyone give me any explanation ?
thanks in advance
.
> m_data=new char[strlen(other.m_data)+1];
> strcpy(m_data,other.m_data);
This is bad with regard to exception safety.
char *tmp = new [strlen(other.m_data) + 1];
strcpy(tmp, other.m_data);
delete[] m_data; // note delete[], not delete
m_data = tmp;
> }
> private:
> char *m_data;
>
> }
>
>
> in the above calss, why memeber function can access the object other's
> private m_data?
> according to Principle of Encapsulation ,a boject can not access other
> object's private memeber.
Because privacy is at the *CLASS* level, not the object level.
Think about it. How would you write a copy constructor or assignment
operator if you couldn't access the private parts of the "other" object?
Because it's a member of the same class. It works this way because it would
be too difficult (or impossible) at compile time to determine which type of
object a pointer in a method was pointing to (IIRC, from Bjarne Stroustrup's
fine book).
Bill
maybe you are right.thank you.
i want to say,how difficult c++ is.
While I don't necessarily disagree, this is a strange choice of language
features to use to claim C++ is difficult. That is how private class
members work in pretty much every language I've encountered that
supports the concept.
By "which type", of course, I meant the invoking object or the one in the
parameter list, or some other object of the same type. I hope that helps.
It's not that it "should" be this way--it's that the alternatives, in view
of the implementation of the language translator, leave few choices.
Bill
How would you implement a copy constructor or copy assignment operator
if an object cannot access the private members of another object of the
same type?
If you have a pointer to an object of the same type as the current
one, how would the compiler know if that pointer is pointing to another
object or to 'this'?