Member Access Control

From RAD Studio
Jump to: navigation, search

Go Up to Member Scope Index

Members of a class acquire access attributes either by default (depending on class key and declaration placement) or by the use of one of the three access specifiers: public, private, and protected. The significance of these attributes is as follows:

  • public: The member can be used by any function.
  • private: The member can be used only by member functions and friends of the class it is declared in.
  • protected: Same as for private. Additionally, the member can be used by member functions and friends of classes derived from the declared class, but only in objects of the derived type. (Derived classes are explained in Base and derived class access.)

Note: Friend function declarations are not affected by access specifiers (see Friends of classes for more information).

Members of a class are private by default, so you need explicit public or protected access specifiers to override the default.

Members of a struct are public by default, but you can override this with the private or protected access specifier.

Members of a union are public by default; this cannot be changed. All three access specifiers are illegal with union members.

A default or overriding access modifier remains effective for all subsequent member declarations until a different access modifier is encountered. For example,

class X {
   int i;    // X::i is private by default
   char ch;  // so is X::ch
public:
   int j;    // next two are public
   int k;
protected:
   int l;    // X::l is protected
};
struct Y {
   int i;    // Y::i is public by default
private:
   int j;    // Y::j is private
public:
   int k;    // Y::k is public
};
union Z {
   int i;    // public by default; no other choice
   double d;
};

Note: The access specifiers can be listed and grouped in any convenient sequence. You can save typing effort by declaring all the private members together, and so on.

See Also