Copy constructors and overloaded assignments.


R. Clayton (rclayton@monmouth.edu)
Thu, 1 Jun 2000 14:33:56 -0400 (EDT)


During class yesterday I said I wasn't sure whether a class's copy constructor
or assignment operater gets called for declarations of the form

  class_name x = y;

It turns out the copy constructor gets called:

  cl cat t.cc
  #include <iostream>

  class test {

    public:

      test(void) {
        cerr << "in test's default constructor.\n";
        }

      test(const test & t) {
        cerr << "in test's copy constructor.\n";
        }

      test & operator=(test & t) {
        cerr << "in test's overloaded assignment operator.\n";
        return t;
        }
    };

  int main(void) {

    test t1;
    test t2(t1);
    test t3 = t2;

    t1 = t3;

    return 0;
    }

  cl g++ -o t -ansi -pedantic -Wall t.cc

  cl ./t
  in test's default constructor.
  in test's copy constructor.
  in test's copy constructor.
  in test's overloaded assignment operator.

  cl



This archive was generated by hypermail 2.0b3 on Fri Aug 11 2000 - 15:25:05 EDT