Why is the copy constructor called when we pass an object as an argument by value to a method?

前端 未结 3 671
无人共我
无人共我 2020-12-06 00:59

Why is the copy constructor called when I pass an object as an argument by value to a function? Please see my below code: I am passing an object of a class as an argument by

3条回答
  •  醉话见心
    2020-12-06 01:42

    As juanchopanza said:, you pass by value, which causes a copy to be made. If you want to prevent this you can pass by reference:

    void display(const ClassA &obj)
    

    On a sidenote: You should declare your copy ctor to take the argument as const reference:

    ClassA(const ClassA &obj)
    

    Otherwise you won't be able to use the copy ctor on named objects marked as const or with temporaries. It also prevents you from accidentally changing the passed in object.

提交回复
热议问题