Topic: Access Control Question


Author: lam@spectra.com (Joshua Lam)
Date: Tue, 21 Sep 93 16:33:47 GMT
Raw View
Hi,

I have a question regarding access control among objects
belonging to the same class.

Consider the following class:

class A
{
  private:
    int x;
  public:
     ...
     A& operator=(A& obj)
     {
         x = obj.x;    // private member x of obj accessed
         return *this;
     }

     void func(A& obj)
     {
         obj.x = x;    // private member x of obj accessed
     }
};

Note that in both the implementations of the overloaded
operator= and the member function func(A& obj), the
private member x of the object obj is accessed directly.

What  rule in C++ allows objects of the same class to
directly access each other's private members via overloaded
operators and member functions?  It seems like objects of
the same class are by default 'friends' of each other, this is
only my observation, please instruct me.

Thanks.

--
Joshua Lam
Spectragraphics Corp., San Diego, CA
email: lam@spectra.com





Author: kanze@us-es.sel.de (James Kanze)
Date: 23 Sep 93 15:26:45
Raw View
In article <1993Sep21.163347.19626@spectra.com> lam@spectra.com
(Joshua Lam) writes:

|> I have a question regarding access control among objects
|> belonging to the same class.

|> Consider the following class:

|> class A
|> {
|>   private:
|>     int x;
|>   public:
|>      ...
|>      A& operator=(A& obj)
|>      {
|>          x = obj.x;    // private member x of obj accessed
|>          return *this;
|>      }

|>      void func(A& obj)
|>      {
|>          obj.x = x;    // private member x of obj accessed
|>      }
|> };

|> Note that in both the implementations of the overloaded
|> operator= and the member function func(A& obj), the
|> private member x of the object obj is accessed directly.

|> What  rule in C++ allows objects of the same class to
|> directly access each other's private members via overloaded
|> operators and member functions?  It seems like objects of
|> the same class are by default 'friends' of each other, this is
|> only my observation, please instruct me.

The basic rule is simple.  Access control is exersed at the class
level, not at the object level.  A member function may access the
private members of any object of its type that it can get its hands
on.  This is not to say that it is necessarily good style to do so,
although in the case of copy construction and assignment operators, it
is often difficult to avoid.
--
James Kanze                             email: kanze@us-es.sel.de
GABI Software, Sarl., 8 rue du Faisan, F-67000 Strasbourg, France
Conseils en informatique industrielle --
                   -- Beratung in industrieller Datenverarbeitung