Class with Pointers and Dynamic Arrays

(solved)
Last edited on
Some comments suggest that you may need a dynamic array (std::vector), so I'll go ahead and use that, otherwise it'd be a pain in the ass to do this exercise.

Club::Club(Club &c)
The copy ctor should be Club::Club(const Club &c). You also need to check for self-assignment: if *this and c are the same object, when you allocate the members array you're also reallocating the one in c, causing a memory leak, and line 48 will copy a newly allocated array (full of default-constructed strings) into itself.
However, if you use std::vector, a plain assignments will copy everything over.

void Club::addMember(string name)
Just push_back() the new member and increment the members count.

void Club::removeMember(string name)
Same situation as adding.
Iterate over the vector to find the matching string, then you can swap that element with the last one and use pop_back(), or store its position and then call erase(position). Remember to decrese the members count.

void Club::loadClub()
before calling addMember() you should check if the string is empty, or you'd add a nameless member before the cycle stops.

string Club::getAllMembers() const
You're returning the first member. What you should do is declare a local string and append the names and commas to it. Then return that. The function isn't asking to cout anything.
Before appending commas check if the name is the last of the members. If it is, don't append the comma.

Club mergeClubs(Club& c1, Club& c2)
I suggest constructing a temporary Club using the copy ctor with c1, then modify that using c2.
Append to the name, add to the members count, then cycle the c2 members and push_back() them into temp's members vector.

Club::~Club()
It's fine, but if you use std::vector there's no need to delete: a vector deletes its content in its own destructor (called automatically after the Club dtor).
Last edited on
Thank you so much!
Topic archived. No new replies allowed.