c++ - Assigning the address of nonconst to a const pointer -



c++ - Assigning the address of nonconst to a const pointer -

i'm studying pointers, constness. confused @ point. learned assigning address of const nonconst pointer prohibited in c++ can solved using const_cast. it's ok.

however, assigning address of nonconst variable const pointer allowed. didn't understand why allowed. please @ below example. in example, ptr pointer const int. however, value ptr points changes. there contradiction here, because const int value ptr points changes. can explain contradiction, or if wrong, can explain why?

#include <iostream> using namespace std; int main() { int year = 2012; const int* ptr = &year; year=100; year=101; cout << *ptr; // 101 printed, value ptr points alter whenever year changes homecoming 0; }

if familiar file access, having pointer-to-const kind of opening file read only. given file handle can utilize reading, doesn't mean file can't changed in other way.

similarly, when have pointer-to-const, have way of reading object, not writing. however, doesn't mean object can't written in other way.

c++ pointers const

Comments

Popular posts from this blog

java - How to set log4j.defaultInitOverride property to false in jboss server 6 -

c - GStreamer 1.0 1.4.5 RTSP Example Server sends 503 Service unavailable -

Using ajax with sonata admin list view pagination -