20-CS-122-001 Computer Science II Spring 2012
Class - Copy Constructor

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

Prev      Next      Lectures      Source

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

class SecondClass {
   char *string;

 public:
   SecondClass (char *);
   SecondClass (SecondClass &);
   char *getString();
   void setString(char *);
   ~SecondClass();
};

SecondClass::SecondClass (char *s) { 
   string = new char[strlen(s)+1];
   strcpy(string, s);
}
	
SecondClass::SecondClass (SecondClass &obj) {   // Copy Constructor
   string = new char[strlen(obj.getString())+1];
   strcpy(string, obj.getString());
   cout << " \n";
}

char *SecondClass::getString() { return string; }

void SecondClass::setString(char *s) { 
   if (string != NULL) delete string;
   string = new char[strlen(s)+1];
   strcpy(string, s);
}

SecondClass::~SecondClass() {
   delete string;
}

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");
   f1(a);
   cout << a.getString();
   getchar();

   f2(&a);
   cout << a.getString();
   getchar();

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