c++ - why do I need both constructor and assignment operator here? -


my code doesn't compile when 1 of these omitted. thought copy assignment operator required here in main(). constructor needed too?

#include <iostream> #include <stdio.h> #include <string.h> using namespace std;  class astring{     public:         astring() { buf = 0; length = 0; }         astring( const char*);         void display() const {std::cout << buf << endl;}         ~astring() {delete buf;}  astring & operator=(const astring &other) {     if (&other == this) return *this;     length = other.length;     delete buf;     buf = new char[length+1];     strcpy(buf, other.buf);     return *this;  }     private:         int length;         char* buf; }; astring::astring( const char *s ) {     length = strlen(s);     buf = new char[length + 1];     strcpy(buf,s); }  int main(void) {     astring first, second;     second = first = "hello world"; // why construction here? ok, know  : p     first.display();     second.display();      return 0; } 

is because here

second = first = "hello world"; 

first temporary created astring::astring( const char *s ) ?

second = first = "hello world"; first create temporay astring "hello world", first assigned it.

so need astring::astring( const char *s ), not copy constructor.


Comments

Popular posts from this blog

java - Jmockit String final length method mocking Issue -

asp.net - Razor Page Hosted on IIS 6 Fails Every Morning -

c++ - wxwidget compiling on windows command prompt -