Interview Question
Financial Software DevelopersTraditionally, const arg to a function signifies that the value passed as const wont be altered within the function (if alteration is attempted, code wont compile).
It is a compilation error to not have const in a constructor that accepts the same object's reference (aka copy constructor). Having a const reference of same object as the only non-defaulted argument is the signature, which C++ compiler uses to qualify a copy constructor and invoke it for copying between objects.
Lamely said, its to avoid compiler error.
I don't think you will get a compilation error if you don't have a const in a copy constructor (at least in vc2008 it's not the case).
IMO, using const in a copy ctor makes it ready to take both const and non-const arguments. Without const, the copy ctor can only take non-const arguments.
e.g.
Foo::Foo(Foo&){...} // ctor without const
const Foo a;
Foo b(a) //error
The copy constructor takes a reference to a const parameter. It is const to guarantee that the copy constructor doesn't change it, and it is a reference because a value parameter would require making a copy, which would invoke the copy constructor, which would make a copy of its parameter, which would invoke the copy constructor, which ...
const has no influence in copy constructor except that it would be resolved at compile time by the compiler. Only thing of importance is passing the argument by reference, if not passed by reference your call to copy constructor will never come back. It would be creating copy for the passed argument, then a temp copy for the copy, another copy of the temp copy and so on...
1. Copy-Constructor without 'const' compiles.
- Maninder Singh June 02, 20092. Copy-Constructor without 'const' is called.
3. 'const' in CC prevents passd object from being modified.
Nothing else.