0

My code doesn't compile when one of these is omitted. I thought only copy assignment operator is required here in main(). Where is 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, now I know  : p
    first.display();
    second.display();

    return 0;
}

is this because here

second = first = "Hello world";

first temporary is created by AString::AString( const char *s ) ?

4pie0
  • 29,204
  • 9
  • 82
  • 118
  • this is an assignment: `second = first /* = "Hello world" */;` You could do it this way with copy constructor only: `AString first("Hello world"); AString second(first);` – Alex Shesterov May 08 '13 at 21:11
  • Your code compiles fine on g++ 4.7 & 4.8... – dyp May 08 '13 at 21:14
  • with both copy and assignment... – 4pie0 May 08 '13 at 21:14
  • Please note [The Rule of Three](https://en.wikipedia.org/wiki/Rule_of_three_(C%2B%2B_programming)) (In C++11 it's The Rule of Five, since we have also the move operators and move assignment operators.) – leemes May 08 '13 at 21:15
  • 3
    You dont have a copy constructor in your code above. You only have an assignment operator and a constructor that happens to take a const char* – Mike Vine May 08 '13 at 21:15
  • In this case I would prefer the [copy-swap-idiom](http://stackoverflow.com/questions/3279543/what-is-the-copy-and-swap-idiom). `second` and `first` are values not pointer so `second = first` is an assignment therefore you need an assignment operator. – andre May 08 '13 at 21:21

1 Answers1

4

second = first = "Hello world"; first create a temporay AString with "Hello world", then first is assigned to it.

so you need AString::AString( const char *s ), but it is not the copy constructor.

yngccc
  • 5,594
  • 2
  • 23
  • 33
  • [expr.ass]/1 "The assignment operator (=) and the compound assignment operators all group right-to-left." – dyp May 08 '13 at 21:20
  • yes, exactly , I have updated question, I overlooked temporary. Don't ask how. – 4pie0 May 08 '13 at 21:21
  • 2
    If you marked your constructor which took a single arg as `explicit` as normally recommended then this code would've given you the error you expect. – Mike Vine May 08 '13 at 21:26