Handout 0

A Class Example


  1. // Handout 0 - myClass.h
  2. #ifndef MYCLASS_H
  3. #define MYCLASS_H
  4. class myClass {
  5. public:
  6. myClass(int); // constructor
  7. ~myClass(); // destructor
  8. void addToMyClass(int);
  9. void subFromMyClass(int);
  10. void showValue();
  11. private:
  12. int daValue;
  13. };
  14. #endif

  1. // Handout 0 - myClass.cpp
  2. // Implementation of the methods defined in myClass.h
  3. #include <iostream.h>
  4. #include "myClass.h"
  5. // constructor
  6. myClass::myClass(int x) {
  7. daValue = x;
  8. cout << "myClass Constructor called" << endl;
  9. cout << "value of daValue is " << daValue << endl;
  10. }
  11. // destructor
  12. myClass::~myClass() {
  13. cout << "myClass Destructor called" << endl;
  14. cout << "the value of daValue is " << daValue << endl;
  15. }
  16. void myClass::addToMyClass(int stuff_to_add) {
  17. daValue += stuff_to_add;
  18. }
  19. void myClass::subFromMyClass(int stuff_to_subtract) {
  20. myClass::addToMyClass(- stuff_to_subtract);
  21. }
  22. void myClass::showValue() {
  23. cout << "the value of daValue is " << daValue << endl;
  24. }
  25. // Handout 0 Class Example - myProgram.cpp
  26. #include <iostream.h>
  27. #include "myClass.h"
  28. int main() {
  29. myClass this_one(1); // create one instance
  30. myClass the_other_one(2); // create a second instance
  31. this_one.addToMyClass(3);
  32. this_one.subFromMyClass(2);
  33. this_one.showValue();
  34. the_other_one.addToMyClass(12);
  35. the_other_one.subFromMyClass(22);
  36. the_other_one.showValue();
  37. return 0;
  38. }

output from the program is as follows:

myClass Constructor called
value of daValue is 1
myClass Constructor called
value of daValue is 2
the value of daValue is 2
the value of daValue is -8
myClass Destructor called
the value of daValue is -8
myClass Destructor called
the value of daValue is 2