20-CS-122-001 Computer Science II Spring 2012
Class - Prototyping

Virtual functions, classes, inheritance, lists, queues, stacks, applications

Prev      Next      Lectures      Source

#include <iostream>
#include <stdio.h>
using namespace std;

// Split class into prototype and methods sections
class FirstClass {
   int number;

 public:
   FirstClass (int);
   int getNumber();
   void setNumber(int);
};

FirstClass::FirstClass (int n) { number = n; }
int FirstClass::getNumber() { return number; }
void FirstClass::setNumber(int n) { number = n; }

void f1 (FirstClass obj) {
   cout << " f1: " << obj.getNumber();
   obj.setNumber(100);
   cout << " " << obj.getNumber();
   getchar();
}

void f2 (FirstClass *obj) {
   cout << " f2: " << obj->getNumber();
   obj->setNumber(100);
   cout << " " << obj->getNumber();
   getchar();
}

void f3 (FirstClass &obj) {
   cout << " f3: " << obj.getNumber();
   obj.setNumber(100);
   cout << " " << obj.getNumber();
   getchar();
}

int main () {
   cout << "======Using Objects Directly\n";
   FirstClass a(5);
   cout << "Value of a = " << a.getNumber() << "\n";
   f1(a);
   cout << "Value of a = " << a.getNumber() << "\n";
   getchar();

   cout << "Value of a = " << a.getNumber() << "\n";
   f2(&a);
   cout << "Value of a = " << a.getNumber() << "\n";
   getchar();

   cout << "======Using Pointers to Objects\n";	
   FirstClass *b = new FirstClass(7);
   cout << "Value of b = " << b->getNumber() << "\n";
   f1(*b);
   cout << "Value of b = " << b->getNumber() << "\n";
   getchar();
	
   cout << "Value of b = " << b->getNumber() << "\n";
   f2(b);
   cout << "Value of b = " << b->getNumber() << "\n";
   getchar();

   cout << "======Send it right on down!\n";
   FirstClass c(9);
   FirstClass *d = new FirstClass(11);
   cout << "Value of c = " << c.getNumber() << "\n";
   f3(c);
   cout << "Value of c = " << c.getNumber() << "\n";
   getchar();
   
   cout << "Value of d = " << d->getNumber() << "\n";
   f3(*d);
   cout << "Value of d = " << d->getNumber() << "\n";
   getchar();
}