C++ Program: “How to pass object to function in C++?“. We can get the solution for this question by using of simple C++ source code. In OOPS concept, Objects are playing a vital role in every program. This CPP tutorial is also talks about passing an object to methods. It can be used as LAB exercise exams. Flow of this program will impress the beginners.
Code Explanation:
There is a class name called PassObj. It has few member variables and member functions. It also has constructor function and destructor function. Scope variable is there for the function calling and its operations. Actually “Fun1” method is used to pass an object. An example program is given at the bottom of this page.
Passing object to function in C++:
[SEE: C Program Tutorials] & [IT Companies Details]
// Karthikh Venkat #include<iostream.h> #include<conio.h> // Class definition class PassObj { int j; public: PassObj(int N); ~PassObj(); void SetV(int N) // Function { j=N; } int GetV() { return j; } }; PassObj::PassObj(int N) { j=N; cout<<"Construct:"<<j<<"\t\n"; } PassObj::~PassObj() { cout<<"Destroy:"<<j<<"\n"; } void Fun1(PassObj Obj1); //Object to function int main() { PassObj O(1); // Object creation Fun1(O); cout<<"Here I is in Main method:"; cout<<O.GetV()<<"\n"; return 0; } void Fun1(PassObj Obj1) { Obj1.SetV(2); cout<<"Here I is local:"<<Obj1.GetV(); cout<<"\n"; }