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


i tried 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 expected. question is: parameter p full copy of object p1? if so, wonder if practice? (i assumed when struct gets big in size, create lot of copy overhead).

there nothing wrong passing structs parameters. passed value in c++ full copy indeed made.

the struct gave in example small it's not problem if pass value. if work bigger data structures, may want pass reference.

beware though, passing reference means if modify struct inside function, original struct modified. sure use const keyword in every case don't modify struct. give immediate information if functions modify information or not.

your example modified work references way :

typedef struct point {     int x;     int y; } point;  void cp(const point& p) // can know cp doesn't modify struct {     cout<<p.x<<endl;     cout<<p.y<<endl; }  void mod_point(point& p) // can know mod_points modifies struct {     p.x += 1;     p.y += 1; }  int main() {     point p1;     p1.x=1;     p1.y=2;     cp(p1);     mod_point(p1);     cp(p1); // output 2 , 3 } 

Comments

Popular posts from this blog

javascript - Enclosure Memory Copies -

php - Replacing tags in braces, even nested tags, with regex -