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

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

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
        


Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.