Home » C++ programs » C++ Class and Objects programs

Passing an object to a Non-Member function in C++

C++ program | Passing an object to a Non-Member function: Here, we are going to learn how to pass an object to a non-member function in C++?
Submitted by IncludeHelp, on September 22, 2018

Here, we have to define a Non-Member Function, in which we have to pass an Object to the class in C++ programming language.

What we are doing in this example?

  • We declared a class named Number that has a private data member named num.
  • We define a Non Member function named myFunction(), that will take two parameters 1) object to class Number and 2) an integer variable number.

Using the example, We have to supply a number (from the main() function) to the class's data member using a Non-Member Function.

Program:

#include <iostream>
using namespace std;

class Number
{
	private:
		int num;
		
	public:
	void setNum(int n)
	{
		num = n;
	}
	
	int getNum(void)
	{
		return num;
	}
};

//a non member function 
void myFunction(class Number N, int number)
{
	//calling setter function and asigning the number 
	N.setNum(number) ;
	//calling getter function and printing the value 
	cout<<"The value is: " << N.getNum() << endl;
}

//Main function
int main()
{
	//local variable of the main 
	int num;
	//object to Number class 
	Number objN;

	num = 10;
	
	//supplying this 'num' to the class by passing  
	//the name to the class in a non memberfunction
	myFunction (objN, num);
	
	return 0;
}

Output

The value is: 10





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.



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.