Iterative Data


/*****************************************************
Example Written in C++
Demonstrates how NOT to handle iterative data as well 
as a few other general DO-NOT's
*****************************************************/

#include 
#include 

using namespace std;

class Person
 {
 private:
   //Our encapsulated data
   string Name;
   int Age;

 public:
   //Default constructor
   Person() : Name(""), Age(0) {};
   Person(string _Name, int _Age) : Name(_Name), Age(_Age) {};

   //Mutator functions allow modification of data
   void SetName(string _Name)
     {
     Name = _Name;
     }
   
    void SetAge(int _Age)
     {
     Age = _Age;
     }

    //Accessor funtions allow access to data value
    string GetName()
     {
     return Name;
     }
    
    int GetAge()
     {
     return Age;
     }
};
        
int main()
  {
  //Create an Array of 3 Persons, 
  //This is BAD! You should not use a constant number for the size
  Person People[3];

  //This is the BAD way, iterative data should use a loop here
  People[0] = Person("", 0);
  People[1] = Person("", 0);
  People[2] = Person("", 0);

  //Loop used but still using literal and using <= shows you might not know 
  // for sure what's happeneing 
  for (int i=0; i <=2; i++) 
    { 
    People[i].SetName("Person"); 
    People[i].SetAge((i + 1) * 9); 
    } 
  //Still using literals, loop is properly used, but should have { } to encampsulate the i 
  i=0; 
  while (i < 3) 
    { 
    cout << People[i].GetName().data() << " is " << People[i].GetAge() << " years old." << endl; 
    i++; 
    } 
  return 0; 
  } 

These pages were edited for style and content by Allan Caine, Laura Drever, Gorana Jankovic, Megan King, and Marie Lewis.
The original authors of these pages were Graeme Humphries, Chantal Laplante, Chris Mills, and Melvin Lenz.

Last Modified: Wednesday, June 7th 23:45:30
Copyright 2000 Department of Computer Science, University of Regina.


[CS Dept Home Page]