C++ facilitates data abstraction and encapsulation by providing access control for members of class types.
For example, if you declare private data members and public member functions, a client program can only access the private members through the public member functions and friends of that class. Such a class would have data hiding because client programs do not have access to implementation details and are forced to use a public interface to manipulate objects of the class.
You can control access to class members by using access
specifiers. In the following example, the class abc has three
private data members a, b, and c, and three public member
functions add(), mult(), and the constructor abc(). The main()
function creates an object danforth of the abc class and then
attempts to print the value of the member a for this object:
// This example illustrates class member access specifiers #include <iostream.h> class abc { private: int a, b, c; public: abc(int p1, int p2, int p3): a(p1), b(p2), c(p3) {} int add() { return a + b + c ; } int mult() { return a * b * c; } }; void main() { abc danforth(1,2,3); cout << "Here is the value of a " << danforth.a << endl; // This causes an error because a is not // a public member and cannot be accessed // directly }
Because class members are private by default, you can omit the
keyword private in the definition of abc. Because a is not a
public member , the attempt to access its value directly causes
an error.
Access Declarations
Inherited Member Access
Class Member Lists
Member Access
Access Specifiers