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 :
//Car class for which we have to implement
// a Smart pointer.
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.
//Smart pointer for class Car
Car * sp;
//Initialize Car pointer when Car
//object is createdy dynamically
CarSP(Car * cptr):sp(cptr)
// Smart pointer destructor that will de-allocate
//The memory allocated by Car class.
printf("Deleting dynamically allocated car object\n");
//Overload -> operator that will be used to
//call functions of class car
Car* operator-> ()
//Create car object and initialize to smart pointer
CarSP ptr(new Car());
//Memory allocated for car will be deleted
//Once it goes out of scope.
Deleting dynamically allocated car object