Re: Simple const-related question
On Feb 18, 6:30 pm, nsdevelo...@yahoo.com wrote:
Is "const Object* pA = new Object(1)" the same as "const Object A(1)"
in terms of creating const objects that should not be modified through
cast-to-non-const pointers. See the following example:
const int* createInt()
{
return new int(1);
}
void myFunc( const int* const_param )
{
cout << "const_param == " << *const_param << endl;
int *non_const_param = const_cast<int*>( const_param );
*non_const_param = 999;
cout << "const_param == " << *const_param << endl;
}
int main(int argc, char* argv[])
{
int a = 1;
const int b = 1;
int* c = new int(1);
const int* d = new int(1);
const int* e = createInt();
myFunc( &a ); // ok
myFunc( &b ); // bad
myFunc( c ); // ok
myFunc( d ); // bad (?)
myFunc( e ); // bad (?)
return 0;
}
I guess my real question is what does "new int(1)" or "new MyObject()"
create - is it always non-const object, or does it depend on the
context as in the following:
MyObject *p1 = new MyObject(); // p1 is non-const
const MyObject *p2 = new MyObject(); // p2 is ???
What about:
MyObject* myFunction()
{
return new MyObject();
}
MyObject* p1 = myFunction(); // p1 is non-const
const MyObject *p2 = myFunction(); // p2 is ???