Is it a good practice to pass struct object as parameter to a function in c++?

user188276 picture user188276 · Apr 27, 2010 · Viewed 29.3k times · Source

I tried an example live below:

typedef struct point
{
    int x;
    int y;
} point;

void cp(point p)
{
    cout<<p.x<<endl;
    cout<<p.y<<endl;
}

int main()
{
    point p1;
    p1.x=1;
    p1.y=2;
    cp(p1);
}

The result thats printed out is:

1
2

which is what I expected. My question is: Does parameter p get the full copy of object p1? If so, I wonder if this is a good practice? (I assumed when the struct gets big in size, this will create a lot of copy overhead).

Answer

CB Bailey picture CB Bailey · Apr 27, 2010

Yes, there's nothing wrong with this and yes, p is a complete copy of p1. I wouldn't call a struct with two ints large, but if the struct does get large and if you don't need to alter it in the function body you could consider passing it by const reference:

void cp(const point& p)
{
    // ...
}