Return to the C++ Demos Home Page

SAMS Teach Yourself C++ in 21 Days

Chapter Eight

Prog 1:  Simple example of Pointers

// Chap 8 TYC++ in 21 by SAMS
// Example code for pointers
//
// Simple assigns and derefs

#include <iostream.h>

typedef unsigned short int USHORT;

int main()
{

  USHORT  myAge;    // a var
  USHORT  * pAge;   // a pointer

  myAge = 5;
  cout << "MyAge : " << myAge << "\n";  // cout var
  pAge = &myAge;
  cout << "pAge : " << *pAge << "\n";   // deref pointer

  *pAge = 7;    // uses pointer ref to reassign val of myAge

  cout << " myAge : " << myAge << "\n";

  myAge = 9;

  cout << " *pAge : " << *pAge << "\n";

  return 1;

  }
Prog 2 : Use of New and Delete
// chap 8 p 2  Pointer Stuff
// Just shows the use of new and delete....
//

#include <iostream.h>

int main()
{

   int localVar = 5;
   int *pLocal = &localVar;     // declarations
   int *pHeap = new int;
   *pHeap = 7;
   
   cout << "local variable : " << localVar << "\n";
   cout << "*pLocal : " << *pLocal << "\n";
   cout << "*pHeap : " << *pHeap << "\n";    // print em out
   
      
   delete pHeap;
   pHeap = new int;    // switch up pHeap
   *pHeap = 9;

   cout << "*pHeap : " << *pHeap << "\n";   // print it out again

   delete pHeap;  // always clean up

   return 0;

}  
Prog 3 :  Simple use of -> operator and pointers for class member data
// chap 8 p 3
// Using pointers for member data and using 
//  the -> operator to access member funcs
//

#include <iostream.h>

   class SimpleCat
   {
      public:

	      SimpleCat();
	     ~SimpleCat();
	      int GetAge() const { return *itsAge; }
	      void SetAge(int Age) { *itsAge = Age; }

	      int GetWeight() const { return *itsWeight; }
	      void SetWeight(int Weight) { *itsWeight = Weight; }

      private:

	      int * itsAge;
	      int * itsWeight;

     }; // end of class SimpleCat

 // define funcs

// constructor
        SimpleCat::SimpleCat()
	{
	   itsAge = new int(2);
	   itsWeight = new int(5);
        }

// destructor
	SimpleCat::~SimpleCat()
	{
	   delete itsAge;
	   delete itsWeight;
        }

// the main prog

int main()
{
	SimpleCat *Frisky = new SimpleCat;
	cout << "Frisky is " << (*Frisky).GetAge() << " old \n";
	cout << "Frisky is " << Frisky->GetAge() << " old \n";

	Frisky->SetAge(7);
	Frisky->SetWeight(12);

	cout << "Frisky is " << Frisky->GetWeight() << " pounds \n";
	cout << "Frisky is " << Frisky->GetAge() << " old \n";

	delete Frisky;

	return 0;
}// end of source

Return to the C++ Demos Home Page