how to use destructor in this case

im new in class, just write a little code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48

#include <iostream>
#include <string>
using namespace std;

class book
	{
	public:
	string name;
	int pages,price;
	book()
		{
			cout<<"\nCreating book with 1st parameter";
			name = "unamed";
			pages = 0;
			price = 0;
		}
	book(int _pages,int _price)
		{
			cout<<"\nCreating book wih 2nd parameter";
			pages = _pages;
			price = _price;
			name = "unamed";
		}
	book(string _name,int _pages, int _price)
		{
			cout<<"\nCreating book with 3rd parameter";
			name = _name;
			pages = _pages;
			price = _price;
		}
	//am i need destructor here ?
	};
int main () 
	{
  	int jawaban;
  	book math;
  	cout<<"("<<math.name<<" "<<math.pages<<" "<<math.price<<")";
  	book cpp(300,50000);
  	cout<<"("<<cpp.name<<" "<<cpp.pages<<" "<<cpp.price<<" )";
  	book art("word art",300,50000);
  	cout<<"("<<art.name<<" "<<art.pages<<" "<<art.price<<" )";
  	
  	cin>>jawaban;
  	
  	//how to delete every book to release used memmory ?
  	return 0;
	}
Last edited on
The sweet thing is, it is already done for you. :-)

The only time you have to worry about deallocating things is when you use new (C++) or malloc() (C).

Hope this helps.
create destructor:

~book (book _object) {
delete _object;
}

calling the destructor:

~book (math);

perhaps?
When only the dynamic allocation.
you will write destructor.


for C;


1
2
int *ptr;
ptr=(int *) malloc(size*sizeof(int));


for C++;

1
2
int *ptr;
ptr=new int[size];
Last edited on
AFAIK the destructor can't have parameters.
Just delete pointers that point to memory allocated with new.
Is really weird that you must call the destructor yourself. (when the objects get out of scope (or when you delete a pointer) the destructor is called)
It is a rare thing for you to need to call the destructor yourself. Let the language do it for you.

If you allocate something in your class, make sure your destructor deallocates it:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
using namespace std;

struct Foo
  {
  int * p;

  Foo( int x )
    {
    // Here we allocate some dynamic memory...
    p = new int;
    *p = x;
    }

  ~Foo()
    {
    // ...so here we must delete it.
    delete p;
    }
  };

int main()
  {
  // Now handling the dynamic memory is done for you -- the class takes care of it all!
  Foo fooey( 42 );
  cout << *fooey.p << endl;
  return 0;
  }

In your case, you never use any dynamically-allocated memory (not directly, anyway ;-), so you don't have to worry about it.

Hope this helps.
thanks friends... it's realy helps........
Topic archived. No new replies allowed.