Yes there is a memory leak in your program because whenever you use new
keyword to allocate some memory then you must always use delete
to free up that memory later when no longer needed. Otherwise you will have a memory leak as in your program. There are 2 ways to solve your problem:
Solution 1: Use delete explicitly
int main()
{
car * ptr = new car("HYUNDAI", 2012);
display(ptr);
//use delete to free up memory
delete ptr; //this will call the destructor
}
Solution 2: Use smart pointers
#include<iostream>
#include<stdlib.h>
#include <memory>
using namespace std;
class car
{
public:
string name;
int num;
public:
car(string a, int n)
{
cout << "Constructor called" << endl;
this->name = a;
this->num = n;
}
~car()
{
cout << "Deleted" << endl;
}
};
void display(std::shared_ptr<car> p)
{
cout << "Name: " << p->name << endl;
cout << "Num: " << p->num << endl;
}
int main()
{
std::shared_ptr<car> ptr = std::make_shared<car>("HYUNDAI", 2012);
display(ptr);
//there is no memory leak
//you don't need to use delete explicitly
}
The advantage of using smart pointer(like shared_ptr or unique_ptr) is that you don't have to free memory explicitly.
Using unique_ptr solution 2 looks like:
#include<iostream>
#include<stdlib.h>
#include <memory>
using namespace std;
class car
{
public:
string name;
int num;
public:
car(string a, int n)
{
cout << "Constructor called" << endl;
this->name = a;
this->num = n;
}
~car()
{
cout << "Deleted" << endl;
}
};
void display(const std::unique_ptr<car> &p)
{
cout << "Name: " << p->name << endl;
cout << "Num: " << p->num << endl;
}
int main()
{
unique_ptr<car> p1(new car("HYUNDAI", 2012));
display(p1);
//there is no memory leak
//you don't need to use delete explicitly
}
Note that in your case you don't need to pass a pointer to display
. You can instead pass the object directly as shown below:
#include<iostream>
#include<stdlib.h>
using namespace std;
class car
{
public:
string name;
int num;
public:
car(string a, int n)
{
cout << "Constructor called" << endl;
this->name = a;
this->num = n;
}
~car()
{
cout << "Deleted" << endl;
}
};
//note pass by value(other way would be to use pass by reference like const car& p)
void display(car p)
{
cout << "Name: " << p.name << endl;
cout << "Num: " << p.num << endl;
}
int main()
{
display(car("HYUNDAI", 2012));
}