OOPortal OOPortal


User Defined Types  «Prev 

C++ Class Diagram Implementation

Point
x: Floating Point
y: Floating Point


In C++, the program corresponding to this diagram would be written like this:
class Point {
  double x;
  double y;
};

Discovering Classes

If you find yourself defining a number of related variables that all refer to the same concept, stop coding and think about that concept for a while. Then define a class that abstracts the concept and contains these variables as data fields.
Suppose you read in information about computers. Each record contains the model name, the price, and a score between 0 and 100. You are trying to find the best result using the least amount of effort.
The product for which the value (score/price) is highest. The following program finds this information for you.

bestval.cpp
#include < iostream >
#include <string >

using namespace std;
int main()
{
 string best_name = "";
 double best_price = 1;
 int best_score = 0;
 bool more = true;
 while (more){
  string next_name;
  double next_price;
  int next_score;
  cout << "Please enter the model name: ";
  getline(cin, next_name);
  cout << "Please enter the price: ";
  cin >> next_price;
  cout << "Please enter the score: ";
  cin >> next_score;
  string remainder; // Read remainder of line
  getline(cin, remainder);
  if (next_score / next_price > best_score / best_price){
   best_name = next_name;
   best_score = next_score;
   best_price = next_price;
  }
  cout << "More data? (y/n) ";
  string answer;
  getline(cin, answer);
  if (answer != "y") more = false;
 }
 cout << "The best value is " << best_name
 << " Price: " << best_price
 << " Score: " << best_score << "\n";
 return 0;
}