Handout 17

A Class Example


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

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