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
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.