Table Of Contents
Previous Section Next Section

Program 84: Construction Project

The student wanted to see when the copy constructor and the operator = were called, so he wrote this program. But the results surprised him. What's happening?

  1 #include <iostream>
  2 /************************************************
  3  * trouble -- A class designed to store a       *
  4  *      single data item.                       *
  5  *                                              *
  6  * Member function:                             *
  7  *      put -- put something in the class       *
  8  *      get -- get an item from the class       *
  9  ************************************************/
 10 class trouble {
 11     private:
 12         int data;       // An item to be stored
 13     public:
 14         trouble(void) { data = 0; }
 15
 16         trouble(const trouble &i_trouble) {
 17             std::cout << "Copy Constructor called\n";
 18             *this = i_trouble;
 19         }
 20         trouble operator = (const trouble &i_trouble) {
 21             std::cout << "= operator called\n";
 22             data = i_trouble.data;
 23             return (*this);
 24         }
 25     public:
 26         // Put an item in the class
 27         void put(const int value) {
 28             data = value;
 29         }
 30         // Get an item from the class
 31         int get(void) {
 32             return (data);
 33         }
 34 };
 35
 36 int main() {
 37     trouble first;      // A place to put an item
 38     first.put(99);
 39
 40     trouble second(first); // A copy of this space
 41
 42     std::cout << "Second.get " << second.get() << '\n';
 43
 44     return (0);
 45 }

(Next Hint 291. Answer 109.)

Table Of Contents
Previous Section Next Section