Re: Simple const-related question
On Feb 19, 1:47 am, "Daniel T." <danie...@earthlink.net> wrote:
On Feb 18, 5:45 pm, nsdevelo...@yahoo.com wrote:
On Feb 18, 6:30 pm, nsdevelo...@yahoo.com wrote:
[...]
MyObject* p1 = myFunction(); // p1 is non-const
const MyObject *p2 = myFunction(); // p2 is ???
Get out of the Java habit of putting () after the class name
when calling new. I'm pretty sure that "new Object();" and
"new Object;" do different things.
If Object has a class type with a user defined constructor, they
do exactly the same thing. Otherwise, new Object() probably
does what you want most of the time.
In answer to your question, the object returned by new is inherently
non-const, but once placed in a const pointer, non-const functions can
no longer be called on that object through that pointer. That doesn't
mean the object is const though, note for example:
Object* o = new Object;
const Object* o2 = o;
o->non_const_func(); // perfectly OK even though the object is being
held in a pointer to const elsewhere.
And to answer the original question, casting away const on the
pointer, and then accessing it, is fully defined behavior.
Technically, you're allowed to allocate a const object, e.g.
"new const Object", but in practice, I don't think any
implementation will make a difference---undefined behavior or
not, the code will actually work exactly as if the object hadn't
been declared const (which, of course, is a permitted behavior
for undefined behavior).
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34