Joe Wang
Joe Wang

Reputation: 21

c++ const Class reference?

I have searched google in a long run, but don't get anything related to my question. Here is the details.

Q:

void myfunc(const myclass& para_ins);
int main(){...
    myclass ins;
    myfunc(ins);
...}

If I pass in a function with a class ins like above, what does const parameter actually do to the ins here? Since it is using reference here, I don't think it will make a copy of ins and make every members in it unchangeable, so does it actually change the original class to const? If so, what if there is a multi-thread program that more than 2 thread manipulate the ins at the same time? If not, what actually happens here?

Upvotes: 1

Views: 2286

Answers (1)

R Sahu
R Sahu

Reputation: 206717

If I pass in a function with a class ins like above, what does const parameter actually do to the ins here?

When a function declares a parameter to be const&, it promises that it will not change the object nor will it call any non-const member function of the object.

Since it is using reference here, I don't think it will make a copy of ins and make every members in it unchangeable

That is correct.

so does it actually change the original class to const?

No, it does not. The original object can still be modified in the calling function if it is not a const object in the calling function.

Upvotes: 1

Related Questions