How to access the Private Member Function in C++
How to access the Private Member Function in C++?
A function declared inside the private access specifier of the class, is known as a private member function. A private member function can be accessed through the only public member function of the same class.
Example:
For example, there is a class named “Student”, which has the following private data members and public member functions:
Private Data members
-
-
- rNo is used to store the roll number of the student.
- perc is used to store the percentage of the student.
-
Public Member functions
-
-
- read() – read() function is used here to read roll number and percentage of the student.
- print() – print() function is used to print roll number and percentage of the student
-
Here, TakeNumbersBegin () and TakeNumbersBeginFinish () are the private member functions which are calling inside public member function in the same class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
#include <iostream> using namespace std; class Student { private: int rNo; float percentage; //private member functions void TakeNumbersBegin(void) { cout<<"Input start..."<<endl; } void TakeNumbersBeginFinish(void) { cout<<"Input end..."<<endl; } public: //public member functions void read(void) { //calling first member function TakeNumbersBegin(); //read rNo and percentage cout<<"Enter roll number: "; cin>>rNo
; cout<<"Enter percentage: "; cin>>percentage; //calling second member function TakeNumbersBeginFinish(); } void print(void) { cout<<endl; cout<<"Roll Number: "<<rNo<<endl; cout<<"Percentage: "<<percentage<<"%"<<endl; } }; //Main code int main() { //declaring object of class student Student object1; //reading and printing details of a student object1.read(); object1.print(); return 0; } |
Output
Input started…
Enter roll number: 5
Enter percentage: 10
Input Finish…
Roll Number: 5
Percentage: 10