Private Member function in C++

How to access private member function of the class?

Although it is a normal practice to place all the data items in a private section and all the functions in public, some situations may require that the functions to be hidden from the outside calls. Tasks such as deleting an account in a customer file or providing increment to and employee are events of serious consequences and therefore the functions handling such tasks should have restricted access. We can place these functions in the private section.

A private member function can only be called by another function that is a member of its class. Even an object can not invoke a private function using the dot operator.

Example:

Class sample
{
int m;
void read (void);
void write (void);
};

If we create an object s1 of class sample, s1.read() or s1.write() is illegal. Because object can not access the private data outside of the class.

One solution to access the private member function is, to call private member function from the member function declared inside the public section of the class.

Example:

Class sample
{
int m;
    void read (void);
public:
    void write (void)
    {
        read();
    }
};

Related posts