I want to use method chaining in C++, but I am worried about memory leakage--I don't know how the garbage collection is handling the intermediary instances returned by the method calls.
Please note, I am intentionally not returning (this) because it is a requirement of the program.
//important to note that in the constructor of Polynomial, I allocate a new
DoublyLinkedList instance as a private member
class Polynomial {
private:
DoublyLinkedList * poly;
//other stuff, constructors and destructor
};
//this is the primary constructor I am using. Notice that I allocated one of its members in the heap
Polynomial::Polynomial(int array [], int size) {
poly = new DoublyLinkedList;
//fill in with the array and size etc.
}
Polynomial::~Polynomial() {
//deallocate the allocated members
}
//------ ADD --------
Polynomial Polynomial::add(Polynomial* polyB){ //does addition by default
//perform add operations and save results into an array called "result" for passing into a Polynomial constructor
return Polynomial(result, maxSize); //will return a NEW instance
}
//example prototypes which return a Polynomial instance (not a pointer to a new instance)
Polynomial Polynomial::add(Polynomial * polyB);
Polynomial Polynomial::subtract(Polynomial * polyB);
Polynomial Polynomial::multiply(Polynomial * polyB);
DoublyLinkedList::DataType polyArrayA [] = {1,3,4};
DoublyLinkedList::DataType polyArrayB [] = {5, 5, 7};
Polynomial p1 = Polynomial(polyArrayA, 3);
Polynomial p2 = Polynomial(polyArrayB, 3);
Polynomial p3 = p1.add(&p1).multiply(&p1).subtract(&p2);
p3.print();
Knowing that garbage collection handles statically declared variables, I decided that the methods could return "Polynomial" versus returning a pointer. The thing is that the Polynomial is a newly instantiated instance (created in the method) and it has a dynamically allocated member--so I need to ensure it's deconstructor is being called.
After each method is called, a new (AFAIK) "statically" declared instance is created and further methods are called using the new instance. But what happens to the intermediate instance?