4pie0
4pie0

Reputation: 29764

why do I need both constructor and assignment operator here?

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 ) ?

Upvotes: 0

Views: 116

Answers (1)

yngccc
yngccc

Reputation: 5694

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.

Upvotes: 4

Related Questions