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

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

Prev      Next      Lectures      Source

// Copy Constructor and Destructor.
// Strings require asking OS for space.  Must use a destructor.
#include <string.h>
#include <iostream>
#include <stdio.h>
#include <string>
using namespace std;

class SecondClass {
   string str;

 public:
   SecondClass (string s) {  str = s;  }
   
   // Copy Constructor
   SecondClass (SecondClass &obj) { str = obj.getString(); }

   string getString() { return str; }

   void setString(string s) { str = s; }

   ~SecondClass() {  }
};

void f1 (SecondClass obj) {
   cout << " f1: " << obj.getString();
   obj.setString("(The string has been reset)");
   cout << " " << obj.getString();
   getchar();
}

void f2 (SecondClass *obj) {
   cout << " f2: " << obj->getString();
   obj->setString("(The string has been reset)");
   cout << " " << obj->getString();
   getchar();
}

void f3 (SecondClass &obj) {
   cout << " f3: " << obj.getString();
   obj.setString("(The string has been reset)");
   cout << " " << obj.getString();
   getchar();
}

int main () {
   cout << "======Using Objects Directly\n";
   SecondClass a("Objects directly");
   cout << "Value of a = " << a.getString() << "\n";
   f1(a);
   cout << "Value of a = " << a.getString() << "\n";
   getchar();

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

   cout << "======Using Pointers to Objects\n";	
   SecondClass *b = new SecondClass("Pointers to objects");
   cout << "Value of b = " << b->getString() << "\n";
   f1(*b);
   cout << "Value of b = " << b->getString() << "\n";
   getchar();
   
   cout << "Value of b = " << b->getString() << "\n";
   f2(b);
   cout << "Value of b = " << b->getString() << "\n";
   getchar();
   
   cout << "======Trying f3\n";
   SecondClass c("Trying...");
   SecondClass *d = new SecondClass("Trying...");
   cout << "Value of c = " << c.getString() << "\n";
   f3(c);
   cout << "Value of c = " << c.getString() << "\n";
   getchar();
	
   cout << "Value of d = " << d->getString() << "\n";
   f3(*d);
   cout << "Value of d = " << d->getString() << "\n";
   getchar();
}