Can anyone tell me how I can pass an object to a C++ function?
Any better solution than mine?
#include<iostream> using namespace std; class abc { int a; public: void input(int a1) { a=a1; } int display() { return(a); } }; void show(abc S) { cout<<S.display(); } int main() { abc a; a.input(10); show(a); system("pause"); return 0; }
Objects as Function Arguments in c++ The objects of a class can be passed as arguments to member functions as well as nonmember functions either by value or by reference. When an object is passed by value, a copy of the actual object is created inside the function. This copy is destroyed when the function terminates.
14. Is it possible that an object of is passed to a function, and the function also have an object of same name? Explanation: There can't be more than one variable or object with the same name in same scope.
Learn: How to pass object as argument into method in C#.Net, in this example, we will be passing object in method. As we know that we can pass primitive (basic) data types in methods as arguments. Similarly, we can pass objects in methods too. Here is an example that will accept objects as arguments in the methods.
You can pass by value, by reference or by pointer. Your example is passing by value.
void show(abc& S) { cout<<S.display(); }
Or, better yet since you don't modify it make it int display() const
and use:
void show(const abc& S) { cout<<S.display(); }
This is normally my "default" choice for passing objects, since it avoids a copy and can't be NULL.
void show(abc *S) { cout<<S->display(); }
Call using:
show(&a);
Normally I'd only use pointer over reference if I deliberately wanted to allow the pointer to be NULL
.
Your original example passes by value. Here you effectively make a local copy of the object you are passing. For large objects that can be slow and it also has the side effect that any changes you make will be made on the copy of the object and not the original. I'd normally only use pass by value where I'm specifically looking to make a local copy.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With