#include <iostream>
#include <string>
usingnamespace 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;
}
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)
#include <iostream>
usingnamespace std;
struct Foo
{
int * p;
Foo( int x )
{
// Here we allocate some dynamic memory...
p = newint;
*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.