Source of nullptr.cpp


  1: //nullptr.cpp
  2: //Illustrates the new C++11 keyword nullptr which should be used as the
  3: //value of any pointer variable to indicate explicitly that it does not
  4: //point to anything. Neither NULL nor 0 should be used in new code.

  6: #include <iostream>
  7: #include <string>
  8: #include <memory>
  9: using namespace std;

 11: class Notification
 12: {
 13: private:
 14:     string s;
 15: public:
 16:     Notification
 17:         (
 18:         const string aString
 19:         ) : s(aString)
 20:     {
 21:         cout << "Notification created!\n";
 22:     }

 24:     ~Notification()
 25:     {
 26:         cout << "Notification deleted!\n";
 27:     }

 29:     void notify() const
 30:     {
 31:         cout << s << "\n";
 32:     }
 33: };

 35: int main()
 36: {
 37:     int* p_int;
 38:     char* p_char;
 39:     double* p_double;
 40:     string* p_string;
 41:     Notification* p_note;

 43:     //C++98
 44:     {
 45:         p_int = NULL;
 46:         p_char = NULL;
 47:         p_double = NULL;
 48:         p_string = NULL;
 49:         p_note = NULL;

 51:         //or
 52:         p_int = 0;
 53:         p_char = 0;
 54:         p_double = 0;
 55:         p_string = 0;
 56:         p_note = 0;
 57:     }

 59:     //C++11
 60:     {
 61:         p_int = nullptr;
 62:         p_char = nullptr;
 63:         p_double = nullptr;
 64:         p_string = nullptr;
 65:         p_note = nullptr;
 66:     }
 67: }