Access modifiers

From Wikipedia, the free encyclopedia
Jump to: navigation, search

Access modifiers (or access specifiers) are keywords in object-oriented languages that set the accessibility of classes, methods, and other members. Access modifiers are a specific part of programming language syntax used to facilitate the encapsulation of components.[1]

In C++, there are only three access modifiers. C# extends the number of them to five, while Java has four access modifiers,[2] but three keywords for this purpose. In Java, having no keyword before defaults to the package-private modifier.

Names of keywords[edit]

C++ uses the three modifiers called public, protected, and private. C# has the modifiers public, internal, protected, private, and protected internal. Java has public, package, protected, and private. The access modifier "package" is the default and used, if any other access modifier keyword is missing. This is not the case in C++, where an absence means that the object is accessed privately. The meaning of these modifiers may differ from one language to another. A comparison of the keywords, ordered from the most restrictive to the most open, and their meaning in these three languages follows. Their visibility ranges from the same class to the package where the class is defined to a general access permission. Below, the maximal access is written into the table.

Keyword C# C++ Java
private class class class
protected internal same assembly and
derived classes
- -
protected derived classes derived classes derived classes
within same package
package - - within its package
public internal same assembly - -
public everybody everybody everybody

Example in C++[edit]

#include <iostream>
using std::cout;
using std::endl;
struct B { // default access modifier inside struct is public
    void set_n(int v) { n = v; }
    void f()          { cout << "B::f" << endl; }
    int m, n; // B::m, B::n are protected
    int x;
struct D : B {
    using B::m;               // D::m is public
    int get_n() { return n; } // B::n is accessible here, but not outside
//  int get_x() { return x; } // ERROR, B::x is inaccessible here
    using B::f;               // D::f is private
int main() {
    D d;
//  d.x = 2; // ERROR, private
//  d.n = 2; // ERROR, protected
    d.m = 2; // protected B::m is accessible as D::m
    d.set_n(2); // calls B::set_n(int)
    cout << d.get_n() << endl; // output: 2
//  d.f();   // ERROR, B::f is inaccessible as D::f
    B& b = d; // b references d and "views" it as being type B
//  b.x = 3; // ERROR, private
//  b.n = 3; // ERROR, protected
//  b.m = 3; // ERROR, B::m is protected
    b.set_n(3); // calls B::set_n(int)
//  cout << b.get_n(); // ERROR, 'struct B' has no member named 'get_n'
    b.f();   // calls B::f()
    return 0;