#include<iostream>
using namespace std;
class car
{
string name;
int num;
public:
car(string a, int n)
{
cout << "Constructor called" << endl;
this->name = a;
this->num = n;
}
void enter()
{
cin >> name;
cin >> num;
}
void display()
{
cout << "Name: " << name << endl;
cout << "Num: " << num << endl;
}
};
int main()
{
// Using new keyword
car *p = new car("Honda", 2017);
p->display();
}
why don't we deallocate space for 'car *p'? If we don't deallocate memory space on the heap, won't there be a memory leak? I am a newbie trying to learn c . I had read that I always had to deallocate space after allocating on heap... I found this code online
CodePudding user response:
Most operating systems will free all memory associated with a program when it ends, so in this case, delete p;
can be extraneous.
This gets a bit more uncertain the lower level you go, especially in embedded systems. Best to get in the practice of using delete
everytime you use new
.
Or don't use new/delete at all when possible.
In your case it is certainly not necessary to use dynamic memory allocation. You could simply write:
int main() {
car p("Honda", 2017);
p.display();
}
If you insisted on using dynamic memory allocation, you might use a smart pointer which will take care of the deallocation for you.
#include <memory>
// car class stuff
int main() {
std::unique_ptr<car> p = std::make_unique<car>("Honda", 2017);
p->display();
}
An aside on your car
class: accustom yourself to using member initializer lists in your constructors.
car(string a, int n)
{
cout << "Constructor called" << endl;
this->name = a;
this->num = n;
}
Becomes:
car(string a, int n) : name(a), num(n)
{
cout << "Constructor called" << endl;
}