Q:

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

belongs to collection: C++ Classes and Object programs

0

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.

 

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 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

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

total answers (1)

C++ Classes and Object programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Accessing Member Function by pointer in C++... >>
<< Create a class Point having X and Y Axis with gett...