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>
#include <string>
using namespace std;

// Using the copy constructor - passing argument by value
class SecondClass {
   string str;

 public:
   SecondClass (string s) { str = s; }

   void string_contents () {
      cout << "Contents of str: " << str << "\n";
   }

   // Copy Constructor
   SecondClass (SecondClass &obj) {
      str = obj.getString();
      cout << " \n";
   }

   string getString() { return str; }

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

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

int main () {
   SecondClass a("Objects directly");
   a.string_contents();
   cout << "a:[" << a.getString() << "]\n";
   f1(a);
   a.string_contents();
   cout << "a:[" << a.getString() << "]\n";
}