Overload -> so that it prevents an attempt to use a null pointer to access a member. - C++ Class

C++ examples for Class:Operator Overload

Description

Overload -> so that it prevents an attempt to use a null pointer to access a member.

Demo Code

#include <iostream>
#include <string>
using namespace std;
// The exception type thrown by the safe pointer.
class bad_ptr {//www  .  ja v a  2 s.  c o  m
   public:
   string msg;
   bad_ptr(string str) { msg = str; }
};
// A class used to demonstrate the safe pointer.
class myclass {
   public:
   int alpha;
   int beta;
   myclass(int p, int q) { alpha = p; beta = q; }
};
template <class T> class safe_ptr {
   T *ptr;
   public:
   safe_ptr() { ptr = 0; }
   // Overload -> so that it prevents an attempt to use a null pointer
   // to access a member.
   T *operator->() {
      if(!ptr != 0) throw bad_ptr("Attempt to use -> on null pointer.");
      else return ptr;
   }
   // Overload the unary pointer operator *.  This operator prevents
   // a null pointer from being dereferenced.
   T &operator*() {
      if(!ptr) throw bad_ptr("Attempt to dereference null pointer.");
      else return *ptr;
   }
   // Conversion from safe_ptr to T *.
   operator T *() { return ptr; }
   T *operator=(T *val) { ptr = val; return ptr; }
};
int main()
{
   // First, use safe_ptr on an integer.
   safe_ptr<int> intptr;
   // Generate an exception by trying to use a pointer before it points to some object.
   try {
      *intptr = 23;
      cout << "The value pointed to by intptr is: " << *intptr << endl;
   } catch(bad_ptr bp) {
      cout << bp.msg << endl;
   }
   // Point intptr to an object.
   intptr = new int;
   // Now the following sequence will work.
   try {
      *intptr = 23;
      cout << "The value pointed to by intpr is: " << *intptr << "\n\n";
   } catch(bad_ptr bp) {
      cout << bp.msg << endl;
   }
   // Now, use safe_ptr on a class.
   safe_ptr<myclass> mcptr;
   // This sequence will succeed.
   try {
      mcptr = new myclass(100, 200);
      cout << "The values of alpha and beta for mcptr are: "
      << mcptr->alpha << " and " << mcptr->beta << endl;
      mcptr->alpha = 27;
      cout << "New value for mcptr->alpha: " << mcptr->alpha << endl;
      cout << "Same as (*mcptr).alpha: " << (*mcptr).alpha << endl;
      mcptr->beta = 99;
      cout << "New value for mcptr->beta: " << mcptr->beta << "\n\n";
   } catch(bad_ptr bp) {
      cout << bp.msg << endl;
   }
   // Create another myclass pointer, but don't initialize it.
   safe_ptr<myclass> mcptr2;
   // The following assignment will throw an exception because
   // mcptr2 points nowhere.
   try {
      mcptr2->alpha = 88;
   } catch(bad_ptr bp) {
      cout << bp.msg << endl;
   }
   delete intptr;
   delete mcptr;
   return 0;
}

Result


Related Tutorials