Search This Blog

Friday, 14 June 2013

Understanding the concept of objects

#include <iostream.h>
#include <math.h>
#include <stdlib.h>

enum Color {Red, Blue, White, Green, Yellow};

const double DUMMY = 0.0; // when data is not needed
const Color DUMMYC = White; // when color is not needed

void show (Color);
void point (char, double); 
void colorPoint (char, double, Color);

void main () {
  
  point('O', DUMMY);
  point('P', DUMMY);
  point('X', 8.0);
  point('P', DUMMY);
  point('Y', 7.0);
  point('P', DUMMY);
  point('X', 2.0);
  point('P', DUMMY);
  point('X', 3.0);
  point('P', DUMMY);
  point('O', DUMMY);
  point('P', DUMMY);
  colorPoint('O',DUMMY,DUMMYC);
  colorPoint('P',DUMMY,DUMMYC);
  colorPoint('C',DUMMY,Blue);
  colorPoint('P',DUMMY,DUMMYC);
  colorPoint('X',2.0,DUMMYC);
  colorPoint('P',DUMMY,DUMMYC);
}

void point (char message, double data) {
  static double x_coord = 0.0;
  static double y_coord = 0.0;
  static double distance = 0.0;

  switch (message) {
  case 'X': // move along x direction
    x_coord = x_coord + data;
    break;
  case 'Y': // move along y direction
    y_coord = y_coord + data;
    break;
  case 'O': // move to origin
    x_coord = 0.0;
    y_coord = 0.0;
    break;
  case 'P': // print coordinates, distance
    cout << "I am currently at x = " << x_coord << ", y = " << y_coord << endl;
    cout << "My distance from the origin is " << distance << endl;
    break;
  default: 
    cout << "Unknown message to point" << endl;
    exit(-1);
  }
  distance = sqrt (x_coord * x_coord + y_coord * y_coord);
  return;
}

void colorPoint (char message, double data, Color color) {
  static Color col = White;

  switch (message) {
  case 'X':
  case 'Y': 
  case 'O':
    point(message,data);
    break;
  case 'C': // set color
    col = color;
    break;
  case 'P': // print coordinates, distance, and color
    point('P',DUMMY);
    cout << "Also my color is ";
    show(col);
    cout << endl;
    break;
  default: 
    cout << "Unknown message to colorPoint" << endl;
    exit(-1);
  }
  return;
}

void show (Color col) {
  switch (col) {
  case Red: 
    cout << "Red";
    break;
  case Blue: 
    cout << "Blue";
    break;
  case White: 
    cout << "White";
    break;
  case Green: 
    cout << "Green";
    break;
  case Yellow:
    cout << "Yellow";
    break;
  }
}

No comments:

Post a Comment