Writing Smart Pointer in C++ for a Specific Class

What is smart pointer and implementation of Smart pointer in C++. This simple smart pointer implementation in C++ is asked in technical interview to know if we know the concept of smart pointer and able to implement it.

Answer: 

Smart pointers are a pointers that get de-allocated by itself, when it goes out of scope and we don’t need to to delete it manually. Generally , in C++ programming we use new and delete to allocate and deallocate memory dynamically / at run time.

When we use “new” to allocate memory, the programmer is responsible to free the memory using delete keyword. Where as this is not the case of smart pointers. In fact, smart pointers are objects which store pointers to dynamically allocated objects.

 

Lets see a simple example to create a smart pointer class.

Consider a class called “Car” having a method Run () as shown below. We will create a smart pointer for this class named CarSP. This smart pointer in C++ program will handle automatic deallocation of memory i.e. for Car object allocated dynamically.

Car Class :

 

Implementation of Smart pointer in C++

In CarSP  smart pointer class, we’ll have a field Car *sp, that hold the pointer of Car object. In the destructor of CarSP, we will write code to delete object of Car class.

To call the function of car class we have to overload arrow operator -> operator, that returns pointer of object Car. Note that After overloading -> only we would be able to use -> on class CarSP that act as a pointer.

Smart pointer class and testing code

 

Output:

       Car Running…

       Deleting dynamically allocated car object