///////////////////////////////////////////////////////// // Pointers.cpp - pointer constness // // // // demo for CSE687 - Object Oriented Design, Sp 2013 // ///////////////////////////////////////////////////////// #include #include int main() { // non-const pointer to non-const contents std::string* pStr = new std::string("non-const string in heap"); *pStr += " - can be changed"; std::cout << "\n " << *pStr << "\n"; std::string* pTemp1 = pStr; pStr = new std::string("can point to another non-const string"); std::cout << "\n " << *pStr << "\n"; delete pTemp1; // non-const pointer to const contents const std::string* pConstStr = new std::string("const string in heap"); // *pConstStr += " - won't compile, can't change contents"; const std::string* pTemp2 = pConstStr; // can change address, e.g., point to new instance pConstStr = new std::string("can point to another const string in heap"); std::cout << "\n " << *pConstStr << "\n"; delete pTemp2; // this is semantically same as previous case std::string const * pAnotherConstStr = new std::string("another const string in heap"); // const pointer to const contents const std::string* const pConstAddressOfConstStr = new std::string("const pointer to another const string in heap"); // *pConstAddressOfConstStr += " - can't be changed so this won't compile"; // pConstAddressOfConstStr = new std::string("attempt to point to new instance"); won't compile std::cout << "\n " << *pConstAddressOfConstStr << "\n\n\n"; delete pStr; delete pConstStr; delete pAnotherConstStr; delete pConstAddressOfConstStr; return 0; }