Code Snippets C/C++ Code Snippets

C++ program to demonstrate calling of private member functions inside public member function.

By: IncludeHelp, On 06 OCT 2016

In this program we will learn how we can access private member functions inside public member function in c++ class?

In this example there is a class A which has two private member functions set_a() and set_b() which will assign values to private data member a and b of class A. And these functions will be accessed inside public member function getValues().

Program will print values of a and b through putValues() which is a public member function of class B.

Hence we will learn private member function can be accessed inside public member function.

C++ program (Code Snippet) – Access private member functions inside public member function in C++ class

Let’s consider the following example:

/*C++ program to demonstrate calling of 
private member functions inside public member function*/

#include <iostream>

using namespace std;

//class definition
class A{
	private:
		int a;
		int b;
		//set value of a
		void set_a(int a){
			this->a=a;
		}
		//set value of b
		void set_b(int b){
			this->b=b;
		}
	public:
		void getValues(int x,int y){
			set_a(x); //calling private member function
			set_b(y); //calling private member function
		}
		void putValues(){
			//printing values of private data members a,b
			cout<<"a="<<a<<",b="<<b<<endl;
		}
};

int main(){
	//creating object
	A objA;
	
	//set values to class data members
	objA.getValues(100,200);
	//print values
	objA.putValues();
	
	return 0;
}

Output

            a=100,b=200
        




Copyright © 2024 www.includehelp.com. All rights reserved.