Public and Private Access Modifiers of a C++ Class

Access Modifiers in C++ control access to Member Variables (Variables Declared in a Class) and Member Functions (Functions Declared in a C++ Class). This sample C++ Code displays how to handle public and private access modifiers. There is another related Access Modifier identified by the keyword protected which will be described later in this website with a introduction of inheritance.

Public and Private Access Modifiers of a C++ Class

Public and Private Access Modifiers of a C++ Class

The above C++ Sample Code displays a simple C++ Class and the main function trying to call public and private member functions. In case you do not specify access modifier in a C++ Class, it is treated as private and the PrivateFunction() as displayed in the given below code snipplet is treated as a private member function of the c++ class……. Note that there is another function named PublicFunction() defined in the C++ class with public as access modifier.

#include "stdafx.h"#include <iostream>class CPublicAndPrivateAccessModifiers{void PrivateFunction(){std::cout << "Output From Private Function of a C++ Class.n";}public:void PublicFunction(){std::cout << "Output From Public Function of a C++ Class.n";}};int _tmain(int argc, _TCHAR* argv[]){CPublicAndPrivateAccessModifiers oCPlusPlusObject;oCPlusPlusObject.PublicFunction();// Given Below Line Generates Compiling Error oCPlusPlusObject.PrivateFunction();//error C2248: 'CPublicAndPrivateAccessModifiers::PrivateFunction' // : cannot access private member declared in //class 'CPublicAndPrivateAccessModifiers'return 0;}

In case you compile the above C++ Sample Code without doing any changes, the C++ Compiler would complain about the function call to the Private Member Function and would give you error details. Learning C++ also needs you to learn and communicate with other tools like Compiler  Linker, Debugger, etc.

In order to compile and run the above project, you would need to comment or remove the function call from the main function ( _tmain as displayed in the above code). You can also call the private member function from within the public Member function. There is no output displayed for this sample C++ project as the code displayed above will not compile unless you make changes to it. Depending on the changes you do, the output of the above C++ project will vary.