Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass object to function in c++?

Tags:

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; } 
like image 493
baljeet Singh Avatar asked Oct 02 '11 11:10

baljeet Singh


People also ask

Can we pass class objects as function arguments?

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.

Is it possible that an object of is passed to a function and the function?

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.

How do you pass an object as an argument in C method?

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.


1 Answers

You can pass by value, by reference or by pointer. Your example is passing by value.

Reference

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.

Pointer

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.

Value

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.

like image 124
Flexo Avatar answered Oct 06 '22 15:10

Flexo