\documentclass[runningheads]{llncs}
\usepackage[T1]{fontenc}
\usepackage{verbatim}
\usepackage{hhline}

\input{psfig.sty}

\begin{document}

\pagestyle{empty}

\newenvironment {src}{\footnotesize \verbatim }{\endverbatim \normalsize}
\newcommand{\func}[1]{\texttt{#1}}
\newcommand{\code}[1]{\texttt{\mbox{#1}}}
\newcommand{\file}[1]{\textit{\mbox{#1}}}
\newcommand{\class}[1]{\texttt{#1}}
\newcommand{\href}[1]{\texttt{#1}}


\mainmatter

\title{Towards More Sophisticated \\ Access Control in C++ }
%       \thanks{Supported by GVOP-3.2.2.-2004-07-0005/3.0}}

\titlerunning{Access Control in C++}


\author{J\'ozsef Mihalicza \and Norbert Pataki \and \'Ad\'am Sipos 
        \and Zolt\'an Porkol\'ab}
\institute{
    Department of Programming Languages and Compilers\\
	E\"otv\"os Lor\'and University, Faculty of Informatics\\
	P\'azm\'any P\'eter s\'et\'any 1/C H-1117 Budapest, Hungary\\
	\email{pocok@inf.elte.hu, patakino@elte.hu, shp@elte.hu, gsd@elte.hu}
}


\maketitle

\begin{abstract}
Encapsulation, information hiding play a crucial role in object-oriented
development. They help in understanding abstractions and ease
code comprehension. They also enforce implementation policies like
using get/set methods. Modern languages have different facilities for
access control from the selective export in Eiffel to the most common
public-protected-private categorization.
In this paper we first compare the existing access strategies in
modern programming languages and describe possible scenarios where 
fine-grained access control is required. Then we show a portable
general solution to extend the relatively simple access control of C++
to a more sophisticated one using only standard language features.
Memberwise access specifications make possible Eiffel-like selective 
export not only for methods but also for nested types and typedefs.
Access groups, roles, and inheritance-driven policies can be used 
to simulate Eiffel-like visibility specifications and more as we 
discuss it in case studies. Our implementation does not require the 
modification of the compiler, we use only standard language elements. 
As our solution introduces minimal syntactic overhead and no runtime 
cost at all, it can be a practical technique for large-scale projects 
where fine-tuned access control is crucial.
\end{abstract}

%--------------------------------------------------------------------

% 2page
\section{Introduction}
\label{intro}

Encapsulation is one of the most fundamental concepts in 
object-oriented programming. It is used to distinguish between the
specification (interface) and the implementation of the class.
The interface is regularly defined in the terms of possible 
services or messages the class offers to its clients. Messages
are specified in forms of their signature. The implementation
of a class defines the internal representation of the objects of
the class and the way the specified messages are handled.
Messages are regularly implemented as member functions or methods. 
The main idea behind encapsulation is to hide as many details of the
representation of the classes as possible. This way we can greatly 
reduce coupling between objects of distinct classes, enforce a
precise definition of class interfaces, and increase reusability.
With the additional help of inheritance and polymorphism, we make
possible the incremental development of software systems.

Encapsulation is usually implemented via specific access control
rules in modern statically typed programming languages. These 
\emph{visibility} rules are typically compiler-checked static 
rules therefore no or minimal runtime activity is involved.
In object-oriented languages, usually data members
are not part of the class interface. In Smalltalk, the member 
variables cannot be accessed outside the class and the implementer 
of the class is forced to write an accessor method to publish the required 
interface. Automatic code generator tools may be used to generate such 
accessory methods.

Visibility rules may affect various language elements. Beside methods
and fields, in many programming languages we can specify enumerators, 
and (nested) structs/classes as members. In some languages, like 
C++, class-level type aliases (typedefs) are also essential.
Visibility of nested types are handled in diverse ways. 

Programming languages follow two main strategies when an object is
referring to a member variable. In languages with \emph{reference 
semantics}, such as Java, the referred object (of a
non-fundamental type) is not physically contained by the referree 
object. In such cases only the \emph{name} of the member is 
protected by the access rules. 
Public methods may return a reference to such objects, and are 
assignable to external variables. It is 
even possible, that the physical object is referred as a member in
two objects belonging to two distinct classes. This problem is
referred as \emph{representation exposure} problem \cite{noble:alias},
and many proposals addressed the problem 
\cite{almeida:balloon,hogg:alias,kniesel:java,skoglund:survey}.

Languages with \emph{value semantic}, like C++, are more secure
in this sense. A member variable is a physical part of the containing 
object; it is a \emph{subobject}, like the base class part. Such
entity belongs to only one containing object.
However, dangerous situations may arise in programming languages
with rich pointer and reference capabilities. In C++ a method may
return with a pointer or reference to a subobject, and may be assigned
to a pointer or reference member of an other object.
Careless destruction of the owner object may lead to dangling
pointers or references and can cause serious malfunctions.

Most modern programming languages export services in an anonymous 
way; i.e. not naming the client classes able to use those services.
An important exception is the Eiffel programming language where 
\emph{selective export} possibilities provides a fine-grained 
description to specify which class components are visible from 
individual client classes. Unfortunately, most current popular 
object-oriented languages lack this feature. In Java, C\#, and  
C++ we are restricted to categorize member access for visibility
classes. In C++ we can use categories, like ,,exporting to all 
clients'' (\code{public}), ,,exporting to the subclasses'' 
(\code{protected}), and ,,exporting to none'' (\code{private}).
Though Java and C\# add additional categories they still  
remain on the base of anonymous category based export.

The C++ programming language also has a special feature called \code{friend}
to specify individual methods or classes to access hidden
data in a class. Unfortunatelly a friend has permission to
access all the fields, methods, nested classes, etc. with 
private or protected visibility.

However, in large projects, when the number of correspondig components
is growing, the class interactions form exponential accretion.  
Here superfluous visibility is a persistent source of design,
implementation, and maintenance problems. On the other hand, a fine-grained 
visibility strategy can utilize the full compile potency of modern
object-oriented languages to filter out unwanted access attempts.

In this article we present a technique to implement Eiffel-like 
selective export facilities in standard C++. Memberwise access 
specifications are available not only for methods but also for 
nested types and typedefs which play important role in generic
libraries. Visibility is specified for individual client classes,
or list of classes explicitly naming them. Various policies 
exist for inheritance hierarchies of clients. Classical visibility
categories, like public and protected are also covered. As C++
is not a pure object-oriented language, visibility for global and 
namespace functions is also implemented.

Named groups of clients, or roles can be used in visibility 
specifications making possible to extend access for a class in a
non-intrusive way. Thus incremental development is also supported. 

The implementation is based template metaprogramming
techniques. As only standard C++ language elements are used, our 
solution is portable, and does not require the modification of the 
compiler, but introduces a minimal syntactic overhead on method calls. 
Since all the visibily controls happen in compile-time, there is no
runtime overhead at all, our approach can be a practical technique for 
large-scale projects where fine-tuned access control is crucial.

This paper is organized as follows. In section \ref{languages} we 
give a brief overview of access methods in currently used and some 
historically important languages. In section \ref{cpp} we examine
visibility rules in C++, and arguing for a more fine-grained solution.
In section \ref{req} we encounter possible scenarios to collect the
requirements for a fine-grained access control. 
Afterwards, in section \ref{impl} we introduces our solution for the
C++ programming language. In section \ref{case} we revisit the 
requirements and show the solution using our techniqe.

%--------------------------------------------------------------------

% 4page
\section{Access Control in Programming Languages}
\label{languages}

Information hiding is one of the fundamental concepts in the 
object-oriented languages. Most object-oriented languages give 
us the opportunity to specify access control. Specifying access 
control is making a decision about the list of entities to whom 
a data member, a method or a nested type is visible.

The simplest solution is provided by modular, non object-oriented
languages, e.g. Ada83, Modula-3. Here members are only \verb|public| or 
\verb|private|. In the object-oriented languages, inheritance requires
additional handling of access rights.
The typical visibility levels are public, private 
and \verb|protected|. A protected member is accessible from the 
current class and from all its subclasses. Simula67, C++,
Ruby, PHP5 and Objective-C support these three visibility levels. 

In C++ we can use keyword \verb|friend| to access private/protected 
member functions, data and classes. In C++ in the case of a \verb|class| 
the default visibility level is private, and in the case of a 
\verb|struct| the default visibility level is public. In C++
we cannot add access modifier to global classes. Global classes
are always accessible, only nested types can be hidden.

\bigskip

\begin{center}
\begin{tabular}{c|c|c|c}
& outside & object & descendants \\ \hline
\verb|public| & accessible & accessible & accessible \\
\verb|protected| & not accessible & accessible & accessible \\
\verb|private| & not accessible & accessible & not accessible directly
\end{tabular}
\end{center}

Let us consider this C++ code as an example

\begin{verbatim}
class Foo
{
public:
  int x; // x is accessible from everywhere
private:
  int y; // y is accessible from class Foo
protected:
  int z; // z is accessible from class Foo
         // and its descendants
};
\end{verbatim}

Ruby differs from other object-oriented languages: access
control is determined dynamically in runtime, not statically.
This can leads to access violations, when the code attempts
to execute a restricted method. Another characteristic of Ruby 
is that a protected method may be called by \emph{any} 
instance of the defining class or its subclasses. A private 
method may be called only within the context of the calling 
object -- it is never possible to access another object's 
private method directly, even if the object is of the same 
class as the caller.

In Simula67 the keyword of private is \verb|hidden|, but
the keyword of protected is \verb|protected|.

Smalltalk has a special access control feature: the data members of
a class are always private, and the methods of a class are always
public.

The export visibility level is a special access modifier. Exported 
member means that, the member can be accessed from outside of the 
executable code. For instance, the D programming language supports 
the export visibility level.

The Java programming language has four visibility levels: 
public, private, protected and \emph{package} visibility. 
Package visibility is the default. The package visibility 
level expresses that the member is accessible from all the 
classes in the same package. With this construct we can 
simulate selective visibility. We locate the classes in 
the same package and use the package visibility to achieve 
the selective visibility. Unfortunately, in this way the 
class itself does not know which classes can access their 
package members. So the groups are described in the hierarchy 
of the packages. Java does not support read/write permissions 
on the shared members, and does not support name aliases. 
In Java we can add access modifier to global classes.
Consider this example code:

\begin{verbatim}
public class Foo {
  int i;           // i is accessible in all classes 
                   // in the same package
  private int j;   // j is accessible in the class Foo
  
  public int k;    // k is accessible everywhere
  
  protected int l; // l is accessible in the class Foo and
                   // Foo's subtypes.
}
\end{verbatim}

C\# is a bit more sophisticated than Java. The C\# has five 
visibility levels: public, private, protected, \verb|internal|
and \verb|protected internal|. Internal visibility level is
similar to Java's package visibility level. Internal members
can be accessed from all classes in the same assembly.
Protected internal members are visible only to the
current assembly or types derived from the containing
class. Because of the similarity to Java's construct,
C\# does not support selective visibility on a level
of class. C\# does not provide name aliasing and 
read/write permissions. Like Java, C\# also supports to
add access modifier to global classes.

Object Pascal has four visibility levels: \verb|published|, 
public, private, and protected. The difference between the 
public and published level is the run-time information about 
the published members.

The Eiffel programming language's access control is a common 
example for a sophisticated tool to define visibility. 
Eiffel's construction is the so-called \emph{selective 
visibility}. In Eiffel we can specify all the
classes that access a member (,,feature''). Two special
keywords are introduced for better expressiveness: \verb|ANY| 
and \verb|NONE|. ANY means that the feature is public. 
NONE means that the feature is accessible from the object 
itself. ANY is the default visibility level. This construction 
describes the access control quite well, because 
the class itself express the visibility straight.
Let us consider this Eiffel code:

\begin{verbatim}
class C
  feature {ANY}
    x: T; -- every classes can access x
  feature {C}
    y: U; -- objects of the class C can access y
  feature {NONE}
    z: V; -- z is accessible only from inside the object
end
\end{verbatim}


UML is a graphical tool to describe classes, objects, the connections 
between them, etc. The Standard UML does have notation for access control.
We can mark public, protected, and private members.
In the paper \cite{ardourel:uml} an extension is advocated in the way of
Eiffel's selective visibility. This extension could be
used for Eiffel code generation.


\section{Visibility in C++}
\label{cpp}


The C++ programming language uses an unnamed, category-based visibility
control. Members exported to all clients (both classes and global/namespace
functions) are \code{public}, members exported only to derived classes (and
friends) must be declared as \code{protected}. \code{Private} members are 
not visible outside of the class (except in friends).

The access of a member of a class can be modified by the keyword \verb|friend|.
With the usage of friend we can access the private and protected
members of a class. The friends are divided into friend functions and friend classes.
Usually we use friend functions when we implement a special global operator.
In C++ we implement the commutative operators (e.g. \verb|operator+|,
\verb|operator==|) and \verb|operator<<| and \verb|operator>>| as global
functions. Global functions cannot access hidden members, but usually we
need them when we implement operators. We do not want to avoid
encapsulation and we do not want to get an overhead by public member function
calls, therefore we have to write friend functions.

Let us consider this example code:

\begin{verbatim}
class Matrix
{
private:
  // ...
public:
  // ...
  friend bool operator==(const Matrix& lhs,
                         const Matrix& rhs);
};

bool operator==(const Matrix& lhs,
                const Matrix& rhs)
{
  //...
}
\end{verbatim}

In this example the \verb|operator==| can access the class Matrix's
private members and implement \verb|operator==| without member
function calls.

Friend classes have a similar meaning. A friend of an other class can
access its private and protected members. Let us consider this code
as an example:

\begin{verbatim}
class Vector {
...
friend class Matrix;
};

class Matrix
{
private:
  // ...
public:
  Vector multiplies(const Vector& v);
};

Vector Matrix::multiplies(const Vector& v)
{
  // here we can access Vector's private members.
}
\end{verbatim}

It does not matter to which part of the interface (public or private) we
place the declaration of friendship. Friend functions belong to
to the declaration of class. A member function of a class may be
the friend of an other class's function. 

The relation of friendship is neither inherited nor transitive.
This is an intentional decision by Bjarne Stroustrup, the designer
of the language \cite{stroustrup:arm}. Consider the following scenario:

\begin{verbatim}
// from ARM:
class ReallySecure
{
    friend class TrustedUser;
private:
    // ...
};

class TrustedUser
{
    //
};
\end{verbatim}

This is just the opposite approach than the one
implemented in Eiffel. However, our solution can cover both cases.

The C++ programming language offers three different forms of inheritance
based on visibility. C++ distinguishes public, private and protected
inheritance. Public inheritance means the well-known notation of
inheritance. Public inheritance creates subtypes, and the derived
class inherits all the public and protected members of the base class.
Contrarily, private inheritance does not create a subtype relationship
between the base and the derived class. Private interface of the derived
class inherits the protected and public interface of the base class.
The private inheritance expresses ,,is-implemented-in-terms-of''.
Here is an example of a private inheritance:

\begin{verbatim}
class Base
{
protected:
  int b;
};

class Derived: private Base
{
  // Here we access b as a private member.
};
\end{verbatim}

Protected inheritance is similar to private inheritance many ways.
Protected inheritance does not create subtype relationship between
the base and derived class. The public and the protected interface
of the base class is accessible as protected members in the derived
class.

Let us consider the following example of protected inheritance:

\begin{verbatim}
class Base
{
protected:
  int b;
};

class Derived: protected Base
{
  // Here we access b as a protected member.
};
\end{verbatim}

Both private and protected inheritance allow overriding
inherited virtual member functions. However, protected
inheritance allows the derived classes of the derived class
to know about the inheritance relationship. Thus the grandkids
are effectively exposed to the implementation details.

%----------------------------------------------------

Scope rules for data hiding were one of the most significant 
new language elements of the module-based languages, like
Clu, Modula, Euclid, and other.

%--------------------------------------------------------------------

% 4page
\section{Access Control Requirements}
\label{req}

In the following we overview the possible 
scenarios of detailed visibilities. We will speak in terms of
the C++ programming language, however, most of the results can be
generalized to most of the statically typed modern object-oriented
languages.

\subsection{Interface function outside class}

A class -- as we learned from object-oriented textbooks -- forms a 
strong cohesion of data structures and operations defined on them.
However, in programming languages like in C++ there is possible to
define functions operating on the class outside of the class scope.
Such global functions -- frequently called as \emph{namespace functions}
-- are lexically not part of the class interface, but de facto they
are.

There are many rational to define namespace functions as part of the
class interface. Some cases the reason is technical, like in the case
of the usual input and output stream operators, \code{operator>>} and
\code{operator<<}. These operators are defined as member of the 
\code{istream} and \code{ostream} classes for inputing and outputing the
built-in types, like \code{char} and \code{int}. However, they are 
defined as namespace functions for other standard library classes,
like \code{string}, and for user defined classes. Implementing the
i/o operations for \code{string} class as members would require the 
inclusion of the \code{<string>} header into the input-output library,
thus we would introduce a highly unwanted dependency and coupling 
between otherwise unrelated classes. For i/o operations of user 
defined classes the 
attempt to create member operators are even more unacceptable; it
requires the modification of pre-defined standard libraries. Thus no
other possibility but defining namespace operators is remained.

Other situation arises when operations with symmetric behaviour are 
defined for classes, like \code{operator+} for \code{string} objects.
Here member operator definition is technically possible, and do not
introduce new dependencies. Consider the following example:

\begin{verbatim}
       string s1 = "hello ", s2 = "world", s;

(1)    s = s1 + s2;
(2)    s = s1 + "world";
(3)    s = "hello " + s2;
    
\end{verbatim}

\noindent
Both member and namespace \code{operator+} work properly
for the first two cases, but only the namespace function
implementation works in (3). In the case of a member operator,
in (2) \code{"world"} has type 
\code{const char[6]} which is automatically converted to
\code{string} in the context of a function argument. 
However, in (3), \code{"hello "} with type \code{const char[7]}
is in a context where no automatic conversion is applied.
When the operator is implemented as a namespace function, 
both arguments appear in the same context, therefore exactly
the same conversions are applied to them. Hence operational
semantics is supported by the implementation syntax.

When an interface function is implemented outside of the
class scope, it requires special rights for accessing hidden
data representation. Unfortunately, the C++ \emph{friend} mechanism
does not provide a satisfying solution. Friends in C++ can access \emph{all}
private methods, incidentally referring forbidden fields. 

\subsection{Interface function for multiple classes}

There are certain situations when we would like to define operations
working on objects from more than one class. A canonical example is
the multiplication between a matrix and a vector object. Here the role
of the matrix and the vector is symmetrical, hard to argue why we would
attach the operation to any of the classes as a member method. To 
avoid unnecessary dependences between matrix and vector, we better 
implement the operation as a namespace function. Naturally, that function 
requires accessing the data representation of both classes.

Pure object-oriented languages, like Java, do not have the concept 
of global or namespace functions. All methods must be implemented as
a member of some class. In that case we have to choose one of the 
classes to place the method into, and we have to allow it to access 
private data of the other class.

\subsection{Access from a specific client} 

Consider the following example:
\footnote{The idea of the example was borrowed from \cite{d:access}.}

\begin{verbatim}
class Person
{
public:
    string name;       /* public for All */
private:
    string address;    /* public for Pal, Bank */
    string nickname;   /* public for Pal */
    string accno;      /* public for Bank */
    string dreams;     /* public for None */
};    

class Bank { };
class Pal { };
\end{verbatim}

\noindent
The class \code{Person} has data fields \code{name}, 
\code{address}, \code{nickname}, the person's bank account number
\code{accno}, and her secret \code{dreams}.
Her name is visible to every client, therefore it is declared as
public. Her dreams are very private. How can the visibility
of the rest of the fields be declared? 

Her address and her account number have to be accessible by her bank; 
her address and nickname be accessible by her pals. Standard C++
\code{friend} declaration is not applicable here: friends have 
\emph{full} access rights to all of the person's private and protected data.
However, a person does not want her bank to know her nickname.
On the other hand even her pals 
must not know her account number, not to mention her dreams.
Here we also require selective access to specify the relationship 
between client functions and individual fields. We have to explicitly 
specify, that \code{nickname} is accessible \emph{only} from inside
\code{Pal} methods, \code{accno} is accessible only from inside
\code{Bank} methods, and \code{address} only from \code{Pal} and
\code{Bank}. Note that publishing \code{address} as a public field
is not the right solution, since new classes may appear in the 
system and we cannot revoke public accessibility later.


\subsection{Access from a list of clients}
\label{list_clients}

In the previous example \code{address} was accessible to both
my bank and my pal. It is desired to encounter a list of
possible clients for a certain field without unnecessary code
duplication. Therefore we have to be able to \emph{group}
client classes for specific access rigths. Eiffel makes possible
grouping of clients via inheritance: we endow a base class with
the required access rights and all the inheritor classes will
possess these rights. In fact, this is very similar to how Eiffel 
(and Java) handle type contstraints on generic parameters. 
Type arguments fulfilling the required constraints on a type 
parameter must implement a common interface or must have a
common base class.

C++ design follows a different pattern: inheritance is not 
considered as a general solution for grouping entities, not even 
in refinement relations. Iterators are an example to this approach:
iterators form a logical chain
of refinements from input iterators to random access iterators, 
but there is no inheritance between iterator implementations.
Thus a more flexible and C++ style solution is to make a listing
of independent classes to specify clients for a certain access.

\subsection{Access from a distinct inheritance hierarchy}

Even if inheritance is not the main feature for grouping, it
could be considered to express access rights for clients in
a classical object-oriented subclass relationship. There might
be a special group of one's pals, classmates, expressed as class
\code{Classmate}, a derived class from \code{Pal}, which also has 
access to one's address.  

In C++, \code{friend} relationship is \emph{invariant} to
subclassing: only explicitly named classes gain special access
for private fields, classes inherited from friends have no
this rights.
Some cases the derived class can access the desired fields via
base class methods: the base declared as \code{friend} has access
to the hidden fields, however this is not always convenient.
Methods in a base class accessing hidden fields might be private,
thus not accessible for the derived, or they might be just not 
efficient for the special purpose of the derived class.

The relationship between enlisted privileged clients and inheritance
is similar to how \emph{exception specification} is defined 
in C++ (and in Java): we can specify a finite number of unrelated
typenames, and individual typenames might identify a group of 
classes via inheritance. At the same time, inheriting access rights
must not be the default policy. 


\subsection{Access by role}

The grouping possibility discussed in section \ref{list_clients}
has a characteristic feature: we define access rights for 
well-known, already existing clients. We can authorize class
\code{Bank} and class \code{Pal} to access the \code{address}
field of the \code{Person}. But what if later we become a client of 
an other bank or an insurance company requires access to my account?  

Grouping by inheritance is not applicable here: we could not 
suppose a common base class for two individual clients. Updating
class \code{Person} to extend the client list for special rights 
is also unfavorable. Incremental development requires a feature make 
client classes able to join a set of access rights in non-intrusive way.
Due to this class \code{Person} might create a \emph{role} for financial
companies, these classes will have a certain set of access rights. Individual classes
can use this role to access specific fields in \code{Person} 

An access role is a "firewall" to separate clients using access
rights and classes that have the accessed members. Thus roles play
an important task in decoupling access-related classes.


%--------------------------------------------------------------------

% 3page
\section{Implementation}
\label{impl}

The basic idea of the implementation is conditional forwarding. We declare each method private, and implement 
public forwarding functions for each of them
containing authorization code. This resembles the decorator pattern
\cite{gamma:patterns}, we decorate the original 
methods with authorization.
The authorization code is a compile time check of a type passed from the caller side. In many cases it is the type 
of the caller class. When the call
is from a global context, or the authorization is not related to the given class, special types are passed.
In most cases the authorization uses compile-time techniques to check the condition, and therefore avoids 
performance overhead, the forwarding function
is optimized out.

Let us see an example. The initial version of the GetAccNo method in the Person class is the following:
\begin{verbatim}
public:
    string GetAccNo() const;
\end{verbatim}
and the corresponding call in Bank:
\begin{verbatim}
	string s = p.GetAccNo();
\end{verbatim}
The forwarding function grants access only to the Bank class:
\begin{verbatim}
private:
    string GetAccNo() const;
public:
    template<class Caller>
    string GetAccNo(Caller* caller)
    {
        CTAssert<IsSameClass<Caller,Bank>::Result>();
        return GetAccNo();
    }
\end{verbatim}
The corresponding call:
\begin{verbatim}
    string s = p.GetAccNo(this);
\end{verbatim}
In this case the type of the caller class is checked. If the function had, two parameters, the forwarding function 
would have three, first the caller,
and then the original two, and so on.

At the caller side it is the developer's responsibility to specify the proper calling type, it is a convention, not 
a strict, forced rule.
The check can be easily bypassed with a cast:
\begin{verbatim}
    string s = p.GetAccNo((Bank*)0);
\end{verbatim}
but this is similar to the proper or improper usage of const\_cast, mutable or
reinterpret\_cast features of the language. It can only be dangerous when being
misused. Later we describe another implementation that can enforce more strict rules, 
but that approach has more limitations and influences to the syntax.

Type forwarding is a bit more difficult, we use a forwarding class instead of a forwarding function:
Let us suppose we have a CreditCardType inner type in the Person class:
\begin{verbatim}
public:
    typedef MyCardType CreditCardType;
\end{verbatim}
the modified code:
\begin{verbatim}
private:
    typedef MyCardType CreditCardType;
public:
    TYPE_AUTH_BEGIN(Person,CreditCardType)
        CompileTimeAssert<IsSameClass<Caller,Bank>::Result> 
		UnauthorizedCaller;
    TYPE_AUTH_END(CreditCardType);
\end{verbatim}
The macros hide the complex parts, the source after macro expansion:
\begin{verbatim}
private:
    typedef MyCardType CreditCardType;
public:
    struct CreditCardType_
    {
    private:
        struct TypeHolder { typedef Person::CreditCardType Type; };
    public:
        template<class Caller>
        struct Type : public TypeHolder
        {
            CompileTimeAssert<IsSameClass<Caller,Bank>::Result> 
		Error_UnauthorizedCaller;
            typedef TypeHolder::Type Result;
        };
    };
    friend struct CreditCardType_;
\end{verbatim}
On the caller side the syntax:
\begin{verbatim}
	Person::CreditCardType* credCard;
\end{verbatim}
changes to the following:
\begin{verbatim}
	Person::CreditCardType_::Type<Caller>::Result* credCard;
\end{verbatim}
%The helper classes are needed, since template friend class specification is not 
%supported by C++.

\subsection{IsInNamespace}
We have shown that access of methods and types can be restricted by compile-time conditions on the caller type or 
on
a type that the caller context provides.
Under these conditions the standard is\_same, is\_base\_of type traits can be used to check against type equality 
or
inheritance relationship.
To implement namespace level visibility we need a compile time facility that can determine whether a certain class
is in the specified namespace.
We show how this facility can be implemented with the help of argument dependent (also called Koenig) lookup
\cite{ansi:cppstandard}.
The rule of argument dependent lookup says that a function of a namespace is visible in an arbitrary context if 
some
of its actual parameters are from its namespace.
Let us consider the following example:
\begin{verbatim}
namespace A {
    struct TypeInA {};
    void foo(int);
    void foo(TypeInA);
}

void bar()
{
    A::foo(5); // valid
    A::foo(TypeInA()); // valid
    foo(5); // invalid
    foo(A::TypeInA()); // valid, argument dependent lookup,
                       // no scope specification needed
}
\end{verbatim}
To determine whether class C is part of namespace N we define two helper functions:
\begin{verbatim}
namespace N {
    template<class T>
    char IsInNamespace_N_helper(T*);
}
long IsInNamespace_N_helper(...);
\end{verbatim}
A call to IsInNamespace\_N with C* type will match the inner function if and only if C is part of the N namespace 
or
the calling context is inside IsInNamespace\_N. To avoid the second case, we implement the namespace predicate 
outside N:
\begin{verbatim}
namespace N { ... }
long IsInNamespace_N_helper(...);
template<class C>
struct IsInNamespace_N {
    enum { Result = sizeof(IsInNamespace_N_helper((C*)0)) == 
	   sizeof(char) };
};
\end{verbatim}
The sizeof trick above is often used in compile-time programming, the function is not really invoked, but the 
overload
resolution is done in compile time.
These helper classes can be hidden by a macro and that way it is only one line of code to implementat the
IsInNamespace predicate for a given namespace:
\begin{verbatim}
	DEFINE_ISINNAMESPACE_PREDICATE(N) // defines IsInNamespace_N 
					  // with all helper functions
\end{verbatim}

\subsection{Strict access control}
The implementation we described earlier relies on the developers obeying the rule that they specify the exact 
calling
context at invocation. An unauthorized caller can easily call any method by 
falsely reporting its class:
\begin{verbatim}
void UnAuthorizedCaller::foo()
{
    C::restrictedfunction(this); // error
    C::restrictedfunction((AuthorizedCaller*)0); // ok
}
\end{verbatim}
By using a different implementation we can avoid this problem, but that technique has some
limitations compared to the original one.
In this approach the caller should provide a Key that can only be accessed by authorized callers:
\begin{verbatim}
public:
    void foo();
\end{verbatim}
becomes
\begin{verbatim}
private:
    void foo();
public:
    class foo_auth {
        class Key {};
        friend class AuthorizedCaller1;
        friend class AuthorizedCaller2;
        friend class C; // this class
    };
    template<class Key>
    void foo() {
        CompileTimeAssert<IsSameClass<foo_auth::Key, Key>::Result>();
        foo();
    }
\end{verbatim}
At the call side the caller should provide the key:
\begin{verbatim}
void AuthorizedCaller1::bar()
{
	C c;
	c.foo<C::foo_auth::Key>();
}
\end{verbatim}
The callers should be friends to see the Key type, therefore we cannot use predicates to select accessors.
On the other hand access groups can be defined by specifying such a Key outside the class. Let us suppose
for example that A, B and C classes work together and would like to call each other's internal methods:
\begin{verbatim}
class InternalAccess
{
    class Key {};
    friend class A;
    friend class B;
    friend class C;
}
\end{verbatim}
The forwarding methods check the Key type and only A, B and C can call the restricted methods:
\begin{verbatim}
    a.restricted<InternalAccess::Key>();
\end{verbatim}


%--------------------------------------------------------------------

\section{Case studies}
\label{case}

In this section we go through the cases of the requirements section and see how our implementation can address 
them.
\subsection{Interface function outside class}
The function outside the class should somehow specify itself as a type. The simplest way is to put the 
implementation
into a class:
\begin{verbatim}
struct outside_Implementation
{
    static void do(C& c)
    {
        c.restricted(this);
    }
};
void outside(C& c)
{
    outside_Implementation::do(c);
}
// ...
    template<class Caller>
    void restricted(Caller* caller)
    {
        CompileTimeAssert<IsSameClass<Caller,outside_Implementation>::Result>();
        restricted();
    }
\end{verbatim}
\subsection{Interface function for multiple classes}
This case is very similar to the previous one, we should create a class for the given role, say 
\code{MathOperations}:
\begin{verbatim}
struct MathOperations {
    static void multiply (Matrix* mtx, Vector* vec, Matrix* result);
};
\end{verbatim}
and provide access to it in the internal methods:
\begin{verbatim}
    template<class Caller>
    void Matrix::getRow(Caller* caller, int iRow, Vector* result)
    {
        CompileTimeAssert<IsSameClass<Caller,MathOperations>::Result>();
        getRow(iRow, result);
    }

    template<class Caller>
    double Vector::getItem(Caller* caller, int iRow)
    {
        CompileTimeAssert<IsSameClass<Caller,MathOperations>::Result>();
        return getItem(iRow);
    }
\end{verbatim}

\subsection{Access from a specific client} 

The name field in the \code{Person} class of the corresponding subsection in the Requirements section is public and 
provides
access to everyone, we don't have to do anything with that.
The other fields are private, but we should provide access to them for some classes:
\begin{verbatim}
    string address;    /* public for Pal, Bank */
    string nickname;   /* public for Pal */
    string accno;      /* public for Bank */
    string dreams;     /* public for None */
\end{verbatim}
The solution:

\begin{verbatim}
public:
    template<class Caller>
    string getAddress(Caller* caller) const {
        CompileTimeAssert<
            IsSameClass<Caller,Bank>::Result ||
            IsSameClass<Caller,Pal>::Result
        >();
        return address;
    }
    // ... getNickName ...
        <IsSameClass<Caller,Pal>::Result>
    // ... getAccNo ...
        <IsSameClass<Caller,Bank>::Result>
    // ... getDreams ...
    string getDreams(Caller* caller) const {
        assert(caller==this);
        return dreams;
    }
\end{verbatim}
Object level access (like dreams) can only be checked in run-time.
\subsection{Access from a list of clients}
When we have multiple clients we can use type list techniques instead of \code{||}-ing \code{IsSameClass} clauses:
\begin{verbatim}
// ... getAddress ...
CompileTimeAssert<
	IsMemberOfTypeList<Caller,
		TypeList2<Pal,Bank> // can be put into a type outside the class if often used
	>::Result
>();
\end{verbatim}
\subsection{Access from a distinct inheritance hierarchy}
To enable not only the authorized class but also its descendants to access our method we should check against
inheritance relationship instead of exact match:

\begin{verbatim}
CompileTimeAssert<SuperSubClass<Authorized,Caller>::Result>();
\end{verbatim}

\subsection{Access by role}

This time the caller does not specify itself by the this pointer, but specifies the role to access the given 
method.
The \code{Person} class defines the financial\_companies access role:
\begin{verbatim}
public:
    class financial_companies_role_type {};
    static financial_companies_role_type* financial_companies_role;
// ... getAccNo ...
	    CompileTimeAssert<IsSameClass<Caller,financial_companies_role_type>::Result>();
\end{verbatim}
The corresponding call:
\begin{verbatim}
void AnyBank::foo(Person* p)
{
    p->getAccNo(Person::financial_companies_role);
}
\end{verbatim}

\subsection{Access limited to method receiver}

As we have the pointer to the caller client, we can implement any object level visibility rules:

\begin{verbatim}
// ... getAccNo ...
        assert(caller==mypreferredbank || caller==mysecondarybank);
\end{verbatim}

\subsection{Interoperability}

We discussed the different access control mechanisms separately, but they often has to be used together.
The compile time checks can be easily combined by the logical operators, and it is true to the run-time checks too.
When different run-time and compile time checks have to be combined together it can happen that we should branch
the run-time checks according to the compile time conditions. Let us suppose a case where \code{Person} provides 
access
to two specific \code{Bank}-s or any of its \code{Relative}-s:

\begin{verbatim}
// ... getAddress ...
        CompileTimeAssert<
            IsMemberOfTypeList<Caller,
			    TypeList2<Bank,Relative>
            >
        >();
        if (IsSameClass<Caller,Bank>::Result) // if is optimized out
            assert(caller==mypreferredbank || caller==mysecondarybank);
\end{verbatim}


%--------------------------------------------------------------------

\section{Related work}
\label{rel}

In all modular and object-oriented languages visibility rules 
are core language elements. The most sophisticated rules can
be found in Eiffel. Bertrand Meyer discusses extensively the 
selective access rules in \cite{meyer:eiffel,meyer:oo}.

Bjarne Stroustrup describes access rules for C++ in \cite{stroustrup:cpp},
and argue for the decisions he made in \cite{stroustrup:arm}.

Abusing visibility rules are tempting for advanced C++ programmers.
Some of the attempts are reviewed by Herb Sutter in 
\cite{sutter:ex1,sutter:ex2}. There is a strong recommendation here 
not to use partial, unmanagable, or compiler-dependent techniques.

Access control in design level is advertized in \cite{ardourel:uml}.
An extension of the standard UML is introduced to describe Eiffel-like
selective export, and tools for generating Eiffel code. Interesting
survey can be found in \cite{skoglund:survey} on the programmers
behaviour using encapsulation in current object-oriented languages and 
in \cite{ahmad:eval} on evaluation of different encapsulation 
techniques.

%--------------------------------------------------------------------

%.5page
\section{Conclusion and Future work}
\label{conc}

Sophisticated access control for object-oriented languages is 
crucial in large-scale industrial projects. In this paper we
enlisted the requirements for fine-grained visibility rules
in object-oriented languages and described techniqes, how they
can be implemented in C++.  Memberwise access 
specifications are available for methods, nested types and typedefs. 
Visibility rules can be specified for individual client classes,
list of classes explicitly named. Inheritance hierarchy in both 
client side and the owner of the hidden data are handled.
Visibility for global and namespace functions is also implemented.
Named groups of clients, or roles can be used in visibility 
specifications making possible to extend access for a class in a
non-intrusive way. Thus incremental development is also supported. 

The implementation is based on standard C++ language elements,
therefore it is highly portable, and does not require modification 
of the compiler. There is no run-time overhead when using our 
solution.

Since our solution introduces a minimal syntactic overhead on 
method calls, our future work is directed towards eliminating 
this problem.


\begin{thebibliography}{99}

\bibitem{noble:alias}
J. Noble, J. Vitek, J. Potter:
Flexible alias protection.
In E. Jul editor, ECOOP 98 - Object-Oriented Programming, 
12th European Conference, Lecture Notes in Computer Science, Vol. 1445.
pp. 158-185., 1998.

\bibitem{almeida:balloon}
P.S. Almeida: Balloon types: Controlling sharing of state in data types.
In M. Aksit, S. Matsuoka, ECOOP 97 - Object-Oriented Programming,
11th European Conference, Lecture Notes in Computer Science, Vol. 1241.
pp. 158-185., Springer, 1997.

\bibitem{hogg:alias}
J. Hogg: Islands: Aliasing protection in object-oriented languages.
In A. Paepcke, editor, OOPSLA 91, Conference Proceedings: 
Object-Oriented Programming Systems, Languages, and Applications, 
pp. 271-285. ACM Press, 1991.

\bibitem{kniesel:java}
G. Kniesel, D. Theisen: JAC - Java with transitive readonly access control.
In Intercontinental Workshop on Aliasing in Object-Oriented Systems, 
IWAOOS'99. 1999.

\bibitem{skoglund:use}
M. Skoglund: Practical Use of Encapsulation in Object-Oriented Programming. 
In B. Al-Ani, H.R. Arabnia, Y. Mun editor, Proceedings of the International
Conference on Software Engineering Research and Practice, SERP '03.
pp. 554-560. CSREA Press, 2003.

\bibitem{skoglund:survey}
M Skoglund: A Survey of the Usage of Encapsulation in Object-Oriented
Programming.
In Workshop on Encapsulation and Access Rights in Object-Oriented Design
and Programming, WEAR 2003.

\bibitem{ardourel:uml}
G. Ardourel, M. Huchard: Class-based Visibility from an MDA Perspective:
From Access Graphs to Eiffel Code.
in Journal of Object Technology, vol. 3, no. 4, April 2004, Special issue:
TOOLS USA 2003, pp. 177-195. 2004. 

\bibitem{stroustrup:arm}
B. Stroustrup, M.A. Ellis: Annotated C++ Reference Manual
Addison-Wesley, 1989.

\bibitem{d:access}
The D programming Language. \\
http://www.digitalmars.com/d/.

\bibitem{ansi:cppstandard}
The C++ Programming Language Standard. (2nd. Ed.)
ISO/IEC 14882. Wiley, 2003.

\bibitem{meyer:oo}
B. Meyer: Object-oriented software construction.
Prentice-Hall, 1997.

\bibitem{meyer:eiffel}
B. Meyer: Eiffel - the language.
Prentice-Hall, 1991.

\bibitem{stroustrup:cpp}
B. Stroustrup: The C++ Programming Language.
Addison-Wesley, 2000.

\bibitem{sutter:ex1}
Herb Sutter: Exceptional C++: 47 Engineering Puzzles, Programming Problems,
and Solutions.
Addison-Wesley, 1999.

\bibitem{sutter:ex2}
Herb Sutter: More exceptional C++.
Addison-Wesley, 2001.

\bibitem{ahmad:eval}
W. Al-Ahmad: Encapsulation in Object-Oriented Programming: Comparison
and Evaluation.
In Workshop on Encapsulation and Access Rights in Object-Oriented Design
and Programming, WEAR 2003.

\bibitem{czar:gener}
K. Czarnezki, U.W. Eisenecker: Generative Programming. 
Addison-Wesley, 2000.

\bibitem{gamma:patterns}
E. Gamma,R. Helm, R., R. Johnson, J. Vlissides: Design Patterns -- 
Elements of Reusable Object Oriented Softwarei. Addison-Wesley, 1995

\end{thebibliography}

\end{document}
