how do you delete an object once you create it?
Printable View
how do you delete an object once you create it?
With what's called a destructor. Your compiler automatically supplies a default destructor if you don't define one, and a destructor is automatically called when your object goes out of scope, like when your program ends.
Try this code:
Code:include <iostream>
using namespace std;
class MyClass
{
public:
MyClass() //Constructor
{
cout<<"Constructor called."<<endl;
}
~MyClass() //Destructor
{
cout<<"Destructor called."<<endl;
}
int number;
};
int main()
{
MyClass an_array[5];
cout<<"In main()."<<endl;
return 0;
}
how do u actually delete the object?
is it anything like
delete <object name>;
free <object name>;
???
Hi,
I was editing my post to address that question specifically. Try re-reading it to see if it explains it now.
thanks for the quick responce, but i was wondering if there was a manual way of deleting it. its not THAT big of a deal, but i have a class just for creating a gui on screen, so once thats one, i just wana have it deleted instead of it hanging around in memory
i COULD call it in another function, but i dont wanna have to write another function specifically just for one object.
Use the delete keyword to free an object. You must pass a pointer to it just as with free(). When deleting an array, use delete[].Code:
MyClass *myclass = new MyClass;
MyClass *myclassarr = new MyClass[10];
delete myclass;
delete[] myclassarr;
thanks!