C++ private member function
Although it is normal practice to place all the data items in private section and all the functions in public, some situations may certain functions to be to be hide(like private data) from the outside calls. Task such as deleting an account of a customer file, or providing increment to any employee are events of serious consequences and therefore the functions handling such tasks should restricted access.
We can place these functions in the private scope
A private member function can only be called by another function that is a member of same or its class.
Even an object cannot invoke a private function using the .(dot) operator.
consider class as defined below
class student
{
roll;
read();
:
update();
write();
};
|
so if s is the object of student class then
s.read();
is illegal however the function read() can be called only by the function update() to update the value of m
sample:: update()
{
read();
}
|
ARRAY WITHIN A CLASS
The array can be used a member variable in a class. The following class definition is valid
const int size=12;
class Array
{
a[size];
:
setvalue();
putvalue();
};
|
The array variable a[] declared as a private member of the class array can be used in the member functions. like any other
variable.we can perform any operations on it. for instance, in the above class definition, the member function setval() sets the values of elements of the array a[], and display() function display the values. similarly we may use other member functions to perform any other operations on th array values
let us take example of Array with in the class
<iostream>
size=5;
student
{
roll_no;
marks[size];
:
getdata ();
tot_marks ();
} ;
student :: getdata ()
{
std::cout<<"\nEnter roll no: ";
std::cin>>roll_no;
(int i=0; i < size; i++)
{
std::cout<<"Enter marks in subject" << (i+1) << ":";
std::cin>> marks[i];
}
}
student :: tot_marks()
{
total=0;
(int i=0; i < size; i++)
std::cout <<"\n\nTotal marks"<< total;
}
main()
{
student stu;
stu.getdata();
stu.tot_marks() ;
}
|
Output:
Enter roll no: 101
Enter marks in subject 1: 67
Enter marks in subject 2 : 54
Enter marks in subject 3 : 68
Enter marks in subject 4 : 72
Enter marks in subject 5 : 82
Total marks = 343
|