Site icon T4Tutorials.com

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

Public Member functions

Here, TakeNumbersBegin () and TakeNumbersBeginFinish () are the private member functions which are calling inside public member function in the same class

#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

Exit mobile version