Kate Rainey
Kate Rainey

Reputation: 1

Syntax and overloading copy constructor

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);
    
    
};

Upvotes: -1

Views: 61

Answers (1)

rturrado
rturrado

Reputation: 8064

That's correct, but it's just a constructor of TODO taking a const reference to a string. You can test it here.

Passing const string& ent (by const reference) is not a bad idea. Another option would be to pass string ent (by value), and move that string when initializing entry, 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).:

// inline TODO(const TODO &) noexcept(false) = default;

The default copy constructor would just copy the members, including the List pointer, but not the List elements (shallow copy). Notice both instances of TODO would be pointing to the same List 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):

    TODO(const TODO& other) {
        std::cout << "custom copy_ctor\n";
        *this = other;
        // Copy listArray elements
        ...
    }

Upvotes: 0

Related Questions