Thursday, 21 September 2017

Smart pointer in C++

/*
 Smart pointer demonstration
 -- smart pointer as name suggest works smart. 
 -- In case of normal pointer, delete is expected to be called explicitley. 
 -- In case pf smart pointer, destruction happens automatically even though some exception occurs 
*/

#include "iostream"
using namespace std;

class Person{
 int age;
 char *name;

 public:
  Person():age(0),name(0){
  }

  Person(int age, char* name):age(age), name(name){

  }
  ~Person(){ }
 
  void display(){
   cout<<"\nAge: "<<age<<"\t"<<name<<endl;
  }
};

class SmartPointer{
 Person *pdata;
 public:
 SmartPointer(Person *pvalue): pdata(pvalue){ }
 ~SmartPointer(){
  delete pdata;
 }
 
 Person& operator*(){
  return *pdata;
 }
 Person* operator->(){
  return pdata;
 }
};
int main(){
 SmartPointer p(new Person(32,"Pavan"));
 p->display();
// delete p;
 return 0;
}
/*
 OUTPUT
[pavan@localhost Home]$ g++ SmartPointer.cpp
[pavan@localhost Home]$ ./a.out 

Age: 32 Pavan
[pavan@localhost Home]$ 

*/

No comments: