1-6) Assignment vs. Initialization


In C++ initialization is NOT the same as assignment

Assignment is done with assignment operator
Initialization invokes a copy constructor



Person p("Lou");

Person q = p;             //initialization
                          //equivalent to Person q(p);

Person q;
q = p;                    //assignment
                          //equivalent to q.operator=(p);



Illustration of cost of assignment vs. cost of initialization using the base member initializer list.
(from C++ advanced course, run with Visual C++ 6.0)

#include <string.h>
#include <iostream.h>

class String {
   public:
      String(void);
      String(const char *s);
   String(const String & s);
      String & operator= (const String &s);
   ~String(void);
   private:
     int len;
     char *data;
};
String::String(void): len(0), data(0) {
 data = new char[1];
 data[0] = '\0';
 cout << "String() \n";
 cout << "     new \n";
}
String::String(const char *s) {
 len = strlen(s);
    data = new char[len + 1];
 strcpy(data,s);
 cout << "String(const char *s) \n";
 cout << "     new \n";
}
String::String(const String & s) {
 len = s.len;
    data = new char[len + 1];
 strcpy(data,s.data);
 cout << "String(const String & s) \n";
 cout << "     new \n";
 cout << "     strcpy \n";

}
String::~String(void) {
 cout << "~String()\n";
 cout << "     delete \n";

 delete [] data;
}
String & String::operator= (const String &s) {
 if(&s != this) {
   len = s.len;
   delete [] data;
   data = new char[len + 1];
   strcpy(data, s.data);
    }
 cout << "String::operator=()\n";
 cout << "     delete \n";
 cout << "     new \n";
 cout << "     strcpy \n";

 return *this;
}
 

class Name {
   public:
    //Note one version of the constructor must be commented out
    //constructor version 1 -using base-member initialization
    Name (const char *t) : s(t) {
    cout << "Name()\n";
    }
    //constructor version 2 -using assignment statement
  /*
    Name (const char *t) {
    cout << "Name()\n";
    s = t;
    }
  */

   ~Name(void) {cout << "~Name()\n";}
   private:
      String s;

};

int main(void) {
   Name person = "Lou";

   return 0;
}



Output using s = t;
 

String()
     new
Name()
String(const char *s)
     new
String::operator=()
     delete
     new
     strcpy
~String()
     delete
~Name()
~String()
     delete


Output using : s(t)
 

String(const char *s)
     new
Name()
~Name()
~String()
     delete