Q:

Example of private member function in C++

belongs to collection: C++ programs on various topics

0

Example:

In this example, there is a class named "Student", which has following data members and member functions:

  • Private
    • Data members
      • rNo - to store roll number
      • perc - to store percentage
    • Member functions
      • inputOn() - to print a message "Input start..." before reading the roll number and percentage using public member function.
      • inputOff() - to print a message "Input end..." after reading the roll number and percentage using public member function.
  • Public
    • Member functions
      • read() - to read roll number and percentage of the student
      • print() - to print roll number and percentage of the student

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program:

#include <iostream>
using namespace std;

class Student
{
	private:
		int rNo;
		float perc;
		//private member functions
		void inputOn(void)
		{
			cout<<"Input start..."<<endl;
		}
		void inputOff(void)
		{
			cout<<"Input end..."<<endl;
		}		
		
	public:
		//public member functions
		void read(void)
		{
			//calling first member function
			inputOn();
			//read rNo and perc
			cout<<"Enter roll number: ";
			cin>>rNo;
			cout<<"Enter percentage: ";
			cin>>perc;
			//calling second member function
			inputOff();				
		}		
		void print(void)
		{
			cout<<endl;
			cout<<"Roll Number: "<<rNo<<endl;
			cout<<"Percentage: "<<perc<<"%"<<endl;
		}
};

//Main code
int main()
{
	//declaring object of class student
	Student std;
	
	//reading and printing details of a student
	std.read();
	std.print();
	
	return 0;
}

Output

Input start...
Enter roll number: 101
Enter percentage: 84.02
Input end...

Roll Number: 101
Percentage: 84.02%

Error: When you try to call the private member function inside the main with the object name.

Example: Changing only main() part

//Main code
int main()
{
	//declaring object of class student
	Student std;
	//trying to call private data member 
	std.inputOn(); //error - because it's a private member
	//reading and printing details of a student
	std.read();
	std.print();
	
	return 0;
}

Output

 
main.cpp: In function 'int main()':
main.cpp:10:8: error: 'void Student::inputOn()' is private
   void inputOn(void)
        ^
main.cpp:47:14: error: within this context
  std.inputOn();
  

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C++ programs on various topics

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Local Class with Example in C++... >>
<< Create an object of a class inside another class d...