Private Member Functions in C++

Although it is normal practice to place all the data items in a private section and all the functions in public, some situations may require certain functions to be hidden (like private data) from the outside calls. Tasks such as deleting an account in a customer file, or providing an increment to an 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 of a class.

A private member function can only be called by another function that is a member of its class. Even an object cannot invoke a private function using the dot operator. For example, consider a class as defined below:

class sample
          int m;
          void read();     //private member function
          void update();
          void write();

If a1 is an object of class sample, then:;

is illegal. However, the function read() can be called by the public member function update() to the read/update the value of m as:

void sample::update()

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *