M
moleskyca1
I cannot figure out why line A a2 = a1; won't call my operator =()?
Program prints:
In A(const char *str)
nothing more! Here is code:
class A {
public:
char *s;
public:
A(): s(NULL) { cout << "In A()" << endl;}
A(const char *str) { cout << "In A(const char *str)" << endl; s = new
char[strlen(str)]; strcpy(s, str); }
A &operator =(const A &rhs);
//~A() { if (s) delete[] s; }
};
A &A:perator =(const A &rhs) {
cout << "in A &operator =(const A &rhs)" << endl;
int size = strlen(rhs.s);
s = new char[size];
strcpy(s, rhs.s);
return *this; }
int main() {
A a1("ABCDE");
A a2 = a1;
return 0;
}
Program prints:
In A(const char *str)
nothing more! Here is code:
class A {
public:
char *s;
public:
A(): s(NULL) { cout << "In A()" << endl;}
A(const char *str) { cout << "In A(const char *str)" << endl; s = new
char[strlen(str)]; strcpy(s, str); }
A &operator =(const A &rhs);
//~A() { if (s) delete[] s; }
};
A &A:perator =(const A &rhs) {
cout << "in A &operator =(const A &rhs)" << endl;
int size = strlen(rhs.s);
s = new char[size];
strcpy(s, rhs.s);
return *this; }
int main() {
A a1("ABCDE");
A a2 = a1;
return 0;
}