×

C++ Programs

C++ Most popular & Searched Programs

C++ Basic I/O Programs

C++ Constructor & Destructor Programs

C++ Manipulators Programs

C++ Inheritance Programs

C++ Operator Overloading Programs

C++ File Handling Programs

C++ Bit Manipulation Programs

C++ Classes & Object 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 [Last updated : March 01, 2023]

How to pass an object to a Non-Member function in C++?

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.

C++ program to pass an object to a Non-Member function

#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

Related Programs

Comments and Discussions!

Load comments ↻





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