26

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;
}
0

1 Answer 1

58

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.

Sign up to request clarification or add additional context in comments.

2 Comments

@Tux-D - I'd tried to avoid the "const pointer" vs "pointer to const" discussion
You're technically correct, but making it much too complicated for a beginner level question. Q: how do I pass an object A: you don't, pass a pointer to the object by value instead is a subtle complication that requires a fairly good understanding to begin with and adds no value at this level beyond simplifiying to say pass by pointer instead.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.