Sunday 28 May 2017

C++ Destructor not working correctly, compile error, just trying to delete a member variable with destr



Following class will be initiated with a member variable newTodayTaskString (string).



When destructing the object I like to delete the string but when compiling the project I get an error message pointing to the destructor delete line saying:




delete: std::string cannot be converted to void



Class:



class TodayTask {
private:
string newTodayTaskString;

public:
TodayTask (string t) : newTodayTaskString (t){}


// Destr.
~TodayTask () {
delete newTodayTaskString;
}

string getTodayTaskString () const {
return newTodayTaskString;
}
};


Answer



delete must be given a pointer, and can only be used to destroy objects created with new.



In this case, the object is a class member, and so will be destroyed automatically. You don't need to do anything with it in the destructor.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...