I have two classes that will create a dynamically allocated cstring (null terminated) of n size upon an object of that class being created. In one class, I have a member function overloading the equivalency operator, and in the other class, I have a non-member function overloading the equivalency operator. I'm using strcmp to compare two cstrings of each class type, and no matter what I initialize the array to, it always returns true.
int main() {
CSTR cstr(5);
CSTR cstr2(6);
if (cstr == cstr2)
cout << "Equal"; //<< Always returns true
else
cout << "False";
cout << "\n\n";
CSTR2 cstr2_1(5);
CSTR2 cstr2_2(6);
if (cstr2_1 == cstr2_2)
cout << "Equal"; //<< Always returns true
else
cout << "False";
return 0;
}
==============================
class CSTR {
public:
CSTR();
CSTR(unsigned int n);
~CSTR();
bool operator ==(const CSTR & rhs);
private:
unsigned int size;
char *elems;
};
============================
CSTR::CSTR() {
size = 0;
elems = new char [0];
}
CSTR::CSTR(unsigned int n) {
if (n > 0) {
size = n;
elems = new char [size];
}
else {
size = 0;
elems = new char [0];
}
}
CSTR::~CSTR() {
delete [] elems;
}
bool CSTR::operator ==(const CSTR & rhs) { //<< Always returns true
return (strcmp(elems, rhs.elems) == 0);
}
===========================================
class CSTR2 {
public:
CSTR2();
CSTR2(unsigned int n);
~CSTR2();
char * getCstrPtr() const;
private:
unsigned int size;
char *elems;
};
bool operator ==(const CSTR2 & CSTR2_1, const CSTR2 & CSTR2_2);
========================================
CSTR2::CSTR2() {
size = 0;
elems = new char [0];
}
CSTR2::CSTR2(unsigned int n) {
if (n > 0) {
size = n;
elems = new char [size];
}
else {
size = 0;
elems = new char [0];
}
}
CSTR2::~CSTR2() {
delete [] elems;
}
char * CSTR2::getCstrPtr() const {
return elems;
}
bool operator ==(const CSTR2 & CSTR2_1, const CSTR2 & CSTR2_2) { //<< Always returns true
return (strcmp(CSTR2_1.getCstrPtr(), CSTR2_2.getCstrPtr()) == 0);
}