Can you help me find the errors with this code:

class MyClass
char * pcMyString;
MyClass( MyOldClass oOld ) { pcMyString = new char[strlen(oOld.pcMyOldString)]; };
MyClass( MyClass * oObj ) { pcMyString = oObj->pcMyString; poMyOld = oObj->poMyOld; };
void calcOffset_Helper() const;
MyOldClass * poMyOld;
bool isStringEmpty() const;
void showString() const;
void reverseString() const;
~MyClass() {};

I need to find the errors, but I can't see anyone

Recommended Answers

All 4 Replies

Does the compiler give you an error?
If so, can you paste it here?

class constructors are private, so you will not be able to use that class for anything.

The second constructor is setting a pointer to some other object -- a very very bad idea because when the other object is destroyed the pointer in MyClass will become invalid. You need to allocate space for the string similar to what you do in the first constructor, then copy the data from oObj into it so that MyClass has complete control and ownership of the data.

The destructor also doesn't delete the pcMyString data, that's a memory leak.

The reverseString() function is marked "const" when it is clearly (from its name) a function that would modify the contained string.

The pointer "poMyOld" is public and uninitialized. It is generally bad to expose a pointer as public because you can't control what it points to, and thus cannot implement any reliable strategy to make sure it doesn't leak memory or corrupt memory.

If the purpose of the first constructor is to copy the string "oOld.pcMyOldString", then it doesn't do that job at all.

The parameter of the first construction should probably be sent by const reference, not by value.

The parameter of the second construction should be const, unless the intent is to modify the object.

As AD said, the shallow copy that is performed in the second constructor is very very bad. You need to do a deep copy.

You ask what are the errors in this code. I don't see any compilation error in the code, but the amount of coding errors is quite astounding. In fact, there are fewer correct lines of code in that piece of code than there are erroneous ones.

Thank you; That was great help.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.