Sunday, February 27, 2011

C++ copy constructor and assign operator



Can you distinguish between copy constructor and assign operator in C++ code? Here's a sample for you. Be aware of knowing that even if it's code format looks assign operator format, it is not assign operator format but copy constructor one.


Download source code : https://sites.google.com/site/gilgildownload/download/IntTest.zip


class Int
{
public:
  // constructor
  Int(const int i = 0)                 { printf("C...
  Int(const Int& r)                    { printf("C...


  // destructor
  virtual ~Int()                       { printf("D...


  // assign operator
  const Int& operator = (const int i)  { printf("A...
  const Int& operator = (const Int& r) { printf("A...
};


void foo()
{
  {
    Int a(1);  // C
    Int b(2);  // C
    Int c(a);  // C
  }


  {
    Int a(3);  // C
    Int b;     // C
    b = 4;     // A
    Int c;     // C
    c = a;     // A
  }


  {
    Int a(5);  // C
    Int b = 6; // C // not assign operator
    Int c = a; // C // not assign operator
  }
}


int main()
{
  foo();
}

No comments: