C++: Public and Private Members

Public and Private Members

In this C++ video, we introduce the ideas of hiding data and simplifying the interface of a class. The simplest method for performing data hiding is to use the keyword private. When private is used in a class, every member after it is hidden from external use unless we reach another access specification. Private data members and private member functions can only be access via member functions.

Below, we have a password class that holds characters in a simple char array. The password is set by the constructor, but can never be accessed directly. Instead, we have our Equal() function which can check whether a password is equal to this one. In this way, we allow passwords to be tested without allowing them to be read.

To illustrate, we have our main function below. First, we create the password object using "XoaX.net" for our constructor argument. Then we create a second password with "XoaX.net" to verify that our check for equality works. The equality check is peformed by our Equal() function. Lastly, we instantiate a third password object with the argument "Xoax.net" that is close but incorrect. So, the second equality test should fail.

Executing the program, we get the expected result.

The use of the keyword private allows us to shield our password from view in this class. However, this example is just for illustration and does not provide any real security for passwords—private is strictly a programming construct.