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

前端 未结 3 669
无人共我
无人共我 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:24

    Because passing by value to a function means the function has its own copy of the object. To this end, the copy constructor is called.

    void display(ClassA obj)
    {
       // display has its own ClassA object, a copy of the input
       cout << "Hello World" << endl;
    }
    

    Bear in mind that in some cases copies may be elided, for instance, if a temporary value is passed to the function.

提交回复
热议问题