I've been experimenting around with the const
modifier, trying to make sure I understand it and clearly I do not. I wrote this program. Note line 28, where I am changing the value of the parameter passed to a copy constructor, and the word const
on line 40:
#include <iostream>
using namespace std;
class MyClass
{
public:
int x;
MyClass (int i)
{
x = i;
cout << "In int constructor. x = " << x << endl;
}
MyClass (const MyClass& f)
{
cout << "In const copy constructor: f.x = "
<< f.x << endl;
x = f.x;
}
MyClass (MyClass& f)
{
cout << "In non-const copy constructor pre-mutation: f.x = "
<< f.x << endl;
x = f.x;
f.x = 8;
cout << "In non-const copy constructor post-mutation: f.x = "
<< f.x << endl;
}
~MyClass ()
{
cout << "In destructor: x = " << x << endl;
}
};
void Func (const MyClass f)
{
cout << "Inside Func: f.x = " << f.x << endl;
}
int main ()
{
MyClass f(4);
cout << "In main before Func call: f.x = " << f.x << endl;
Func (f);
cout << "In main after Func call: f.x = " << f.x << endl;
return 0;
}
I have the const
modifier on line 40, which I believed made it so f
could not be changed and thus I believed would require a call to a copy constructor that couldn't change the parameter passed to it. I wrote a copy constructor that was allowed to change its parameter passed to it and one that wasn't allowed to, using the const
keyword. Here's the output.
In int constructor. x = 4
In main before Func call: f.x = 4
In non-const copy constructor pre-mutation: f.x = 4
In non-const copy constructor post-mutation: f.x = 8
Inside Func: f.x = 4
In destructor: x = 4
In main after Func call: f.x = 8
In destructor: x = 8
My question is: why was the non-const copy constructor called rather than the const copy constructor, given the word const
on line 40? Thank you.