Practice 1
if (clazz1 == clazz2)
clazz1 = clazz2;
if (clazz1 == clazz3)
uses the const object for the 2nd operand. However, the operator == is defined to take un-const arg). Same for clazz1 == clazz2. Although the variable defined as the reference can be used as a normal variable and it is very convenient, it is not very safe. Hence, if you're not changing the variable when it's passed to other functions, constshould be attached to make sure that it wont' be modified.
Hence, the provided code should work by changing the definition of operator= andoperator== as:
void operator=(const MyClass &clazz){...
void operator==(const MyClass &clazz){...
Practice 2
The caller of both operator = and == would not know whether the content of the arg might be changed or not. Hence, you should put const to the args. Moreover, operator= needs to modify its own member variable, hence
void operator=(const MyClass &clazz) const {...
should be
void operator=(const MyClass &clazz) {...
Practice 3
The following function is defined as const it's not allowed to modify name.
void setName(string n) const {
name = n;
}
Even if a function is defined as const, you can allow certain member variable to be modified by adding mutable to the declaration of the variable:
int num1;
float num2;
mutable string name;
Practice 4
#include <iostream>
using namespace std;
// a class to store a dynamically generated char array.
class MyArray {
char *ptr;
MyArray(){}
public:
// constructor, that takes one arg.
// *p is the string to be stored in the dynamically allocated char array
MyArray(char *p) {
const int size = strlen(p);
try {
ptr = new char[size + 1];
if (ptr == NULL)
throw p;
} catch (...) {
cerr << "memory error" << endl;
exit(1);
}
strcpy(ptr, p);
}
char *getstr() {return ptr;}
MyArray &operator=(const MyArray &ra) {
if (this == &ra)
return *this;
delete[] ptr;
const int size = strlen(ra.ptr);
try {
ptr = new char[size + 1];
if (ptr == NULL)
throw ptr;
} catch (...) {
cerr << "Memory Error" << endl;
exit(1);
}
strcpy(ptr, ra.ptr);
return *this;
}
~MyArray() {
cout << "MyArray::Destructor : " << ptr << endl;
delete[] ptr;
ptr = NULL;
}
};
int main() {
MyArray mArray1("mArray1's string");
MyArray mArray2("mArray2's string");
cout << "mArray1's content = " << mArray1.getstr() << endl;
cout << "mArray2's content = " << mArray2.getstr() << endl;
cout << "mArray2's value after self copy: " << (myArray2 = myArray2).getstr() << endl;
cout << "mArray1's value after copy from mArray2: " << (myArray1 = myArray2).getstr() << endl;
return 0;
}