Hello, I have a question about constructors. I've stumbled upon a piece of code that I don't quite understand. Here's the code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
class cls
{
public:
cls( ){ cout<<”constructor\n”;}
cls(cls &c){cout<<”copy constructor\n“;}
};
int f(cls c){ return 1;}
int main()
{
cls c;
f(c);
}
When I compile and run this code, 2 things happen :
- it prints the "constructor" string because a new object of that class it's created;
- it prints the "copy constructor" string. Why it's that ?
I've observed that if I change the function to :
int f(cls &c){ return 1;}
the "copy constructor" string isn't printed anymore.
Can anyone explain this for me please ? Thanks in advance and sorry for my bad English.
Indeed, so basically, this is what's called "Passing by Value". It's the default way of passing function parameters, so as JoR said, c is copied to the function parameter.
If you change your function f to int f(cls& c), then its parameter is now a reference parameter (see "Passing by Reference"). If you run the code now, 'c' is passed by reference and not by value, and thus the copy constructor is not called.