Overload the -> operator

Previous      Next      acount.1.cc

#include <string.h>
#include <iostream>
using namespace std;

class Account {
   double account_balance;
   char *owner;

public:
   Account (const char *name) {
      owner = new char[strlen(name)+1];
      strcpy(owner, name);
      account_balance = 0;
   }
   
   double balance () { return account_balance; }
   
   void deposit (double amount) { account_balance += amount; }

   char *get_name() { return owner; }
};

class AccountPtr {
   unsigned cnt;  // Keeps track of the number of times account accessed
   Account *ptr;
			 
public:
   AccountPtr(const char *name) {  ptr = new Account(name);  cnt = 0; }

   // The important one
   Account *operator->() { cnt++;  return ptr;  }

   int get_count() { return cnt; }

   double balance () { return ptr->balance(); }

   void deposit (double amount) { ptr->deposit(amount); }
};

int main () {
   AccountPtr john("John");
   john->deposit(10.19);
   cout << "$" << john.balance() << "\n";
   john->deposit(21.30);
   cout << "$" << john.balance() << "\n";
   john->deposit(87.29);
   cout << "$" << john.balance() << "\n";
   cout << "Total number of deposits to " << john->get_name() 
	<< "'s account: " << john.get_count() << "\n";
}