Handout 0
A Class Example
- // Handout 0 - myClass.h
-
- #ifndef MYCLASS_H
- #define MYCLASS_H
-
- class myClass {
- public:
- myClass(int); // constructor
- ~myClass(); // destructor
- void addToMyClass(int);
- void subFromMyClass(int);
- void showValue();
- private:
- int daValue;
- };
-
- #endif
- // Handout 0 - myClass.cpp
-
- // Implementation of the methods defined in myClass.h
-
- #include <iostream.h>
- #include "myClass.h"
-
- // constructor
- myClass::myClass(int x) {
- daValue = x;
- cout << "myClass Constructor called" << endl;
- cout << "value of daValue is " << daValue <<
endl;
- }
-
- // destructor
- myClass::~myClass() {
-
- cout << "myClass Destructor called" << endl;
- cout << "the value of daValue is " << daValue <<
endl;
- }
-
- void myClass::addToMyClass(int stuff_to_add) {
- daValue += stuff_to_add;
- }
-
- void myClass::subFromMyClass(int stuff_to_subtract) {
- myClass::addToMyClass(- stuff_to_subtract);
- }
-
- void myClass::showValue() {
- cout << "the value of daValue is " << daValue <<
endl;
- }
-
- // Handout 0 Class Example - myProgram.cpp
-
- #include <iostream.h>
- #include "myClass.h"
-
- int main() {
-
- myClass this_one(1); // create one instance
- myClass the_other_one(2); // create a second instance
-
- this_one.addToMyClass(3);
- this_one.subFromMyClass(2);
- this_one.showValue();
-
- the_other_one.addToMyClass(12);
- the_other_one.subFromMyClass(22);
- the_other_one.showValue();
-
- return 0;
- }
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