Disclaimer. This is for an homework assignment (due in two weeks) and this is just one tiny aspect of the entire project that has been a major headache for me., I just would like some insight on the implementation of setting and getting a dynamic char array in the below structure.
I realize I need a setter and a getter method.
Also the string being passed in. A c-string will be random in length, so assuming this would need an dynamic char array.
Any advise or resources will be helpful. Thanks in advance.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
class item
{
public:
item();
~item();
item(const item& other);
item& operator=(const item& other);
//setter for Name ?
// getter for Name ?
private:
char* name;
double weight;
};
Why are you using C strings when you'lll need dynamic memory allocation. std::strings provides a better implementation. Or does your project specifications tie you down to C strings?
void item::getName(char * name) const
{
//returns name
strcpy(name, this->name);
}
void item::setName(char * name)
{
//release the exisisting memory if there is any
if(this->name)
delete [] this->name;
//set new name
this->name = newchar[strlen(name)+1];
strcpy(this->name, name);
}
You can safely reduce this to: delete[] this->name;
What if name isn't null terminated? I would change the function signature to: void item::setName(constchar* name, size_t size)
then take advantage of the size parameter, which should be the size of the string passed. We pass const for name so we assure the user of said function that we do not modify the buffer passed. Instead of using strlen and strcpy, you would instead use size and strncpy.
Sorry, I thought I had included a short explanation. The check simply checks the pointer for being valid. A valid pointer is anything that isn't a null pointer. delete already makes a check for null pointers whenever you pass a pointer to it. If the pointer passed is a null pointer, it's a no-op. By having the if statement there, you're simply checking for null pointers twice. Instead, you should simply make sure the pointer is a null pointer when it's not valid and pass the pointer to delete directly.