I am new to the topic of overloading copy constructors and I just wanted someone to look at my code for my class and see if I am overloading my copy constructor correctly. It is only using a single string as user input. Also, do I need the '&' or not?
class TODO {
private:
string entry;
public:
List* listArray = nullptr;
int itemCount = 0, currInvItem = 0;
int maxLength = 22;
TODO() { entry = ""; };
TODO(const string& ent) { setEntry(ent); }; // Is this correct?
void setEntry(string ent) { entry = ent; };
string getEntry() const { return entry; };
void greeting();
void programMenu();
void newArray();
void getList();
void incList();
void delTask();
string timeID();
string SystemDate();
friend istream& operator >>(istream& in, TODO& inv);
friend ostream& operator <<(ostream& out, TODO& inv);
void componentTest();
void setTask(string a);
string getTask();
bool validTask(string a);
bool notEmpty(string e);
};
That's correct, but it's just a constructor of
TODO
taking a const reference to astring
. You can test it here.Passing
const string& ent
(by const reference) is not a bad idea. Another option would be to passstring ent
(by value), and move that string when initializingentry
, i.e.: entry{ std::move(ent) }
. As here.The class TODO has a default copy constructor. Check the line at the Insight window here (you'll have to click Play first).:
The default copy constructor would just copy the members, including the
List
pointer, but not theList
elements (shallow copy). Notice both instances ofTODO
would be pointing to the sameList
elements, and any operation on them would affect both instances.Should you want to implement a custom copy constructor, the syntax would be (see here):