Reputation: 2928
From my testing, an object can still be modified after creation.
//Let's use this copy constructor as an example:
Foo::Foo( const Foo& F )
{
var = F.var;
}
//With this code:
Foo f1;
const Foo f2(f1); //No Error?
There is no initializtion list, so f2 is being modified after it was created. So if the members of Foo are still modifiable, what is being made constant?
Upvotes: 1
Views: 92
Reputation: 227618
f2
is not being modified after being created. This line
const Foo f2(f1);
creates f2
, and f2
can modify it's own data members in the body of the constructor. Once the body of the constructor is exited, the object is fully constructed and cannot be modified.
There are a couple of points worth mentioning:
var
were const
, then you would have to initialize it in the constructor's initialization list, and it could not be modified in the body of the constructor. This is independent of whether you have a const
Foo
instance or not.var
were declared mutable
, then it would be possible to modify a const Foo
instance via a const
method that modifies var
.Upvotes: 2
Reputation: 340516
An object's lifetime does not start until its constructor has completed (C++03 3.8 "Object lifetime"), so until that point there's nothing to be const
. In particular, C++03 12.1/4 "Constructors" says:
const
andvolatile
semantics (7.1.5.1) are not applied on an object under construction. Such semantics only come into effect once the constructor for the most derived object (1.8) ends.
Upvotes: 1