Write Smart Pointer in C++ for a specific class

Smart pointer implementation in C++ interview question is asked in technical job interview to freshers and experienced IT professionals to know if they are capable to implement a smart pointer class in C++.


Answer: This simple smart pointer implementation in C++ is asked in technical interview to know that we have concept of smart pointer and able to implement it. This Smart pointer class will deallocate memory itself when it goes out of scope and we don’t have to delete it manually.

As an example, let’s have a class called “Car” with a method Run (); and since, explicitly, we don’t want to deallocate memory for Car class, we will have a smart pointer, called CarSP that will handle automatic deallocation of memory i.e. for Car object allocated dynamically.


Car Class :


CarSP, car smart poitner implementation. In this class we’ll have a field Car *sp, that hold the pointer of Car object.In destructor CarSP, we will be deleting object of Car class.

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


Smart pointer in C++ implementation and test program with comments.



       Car Running…

       Deleting dynamically allocated car object