just trying to wrap my head around how I go about deallocating memory of new objects which are passed as arguments.
Say I have a Link class defined like this:
class Link{
public:
Link(const std::string& value, Link* previous = nullptr, Link* successor = nullptr) : _value{ value }, _previous{ previous }, _successor{ successor }{}
Link* Insert(Link* new_link);
Link* getPreviousLink() const{ return _previous; }
Link* getSuccessorLink() const{ return _successor; }
std::string _value;
private:
Link* _previous;
Link* _successor;
};
And then I have Link* Insert(Link*) defined like so:
Link* Link::Insert(Link* new_link){
if(!new_link){ return this; }
if(!this){ return new_link; }
new_link->_successor = this;
if(_previous){ _previous->_successor = new_link; }
new_link->_previous = _previous;
_previous = new_link;
return new_link;
}
And then in my main(), I do the following:
int main(){
Link* Cars = new Link("Ford");
Cars = Cars->Insert(new Link("Ferrari"));
Cars = Cars->Insert(new Link("Hummer"));
Cars = Cars->Insert(new Link("Volvo"));
}
I've created a Link pointer called 'Cars' and allocated a new Link on the heap with a value of "Ford". I then assign my Cars pointer to a new Link returned from Insert(). Repeat this step 2 more times.
My question is, how do I delete or free the memory allocated when I pass the new Link objects as arguments? Do I do so in the destructor of Link? If I just delete my Cars pointer, it wouldn't deallocate the other Links.