Commit 22c04946 authored by Tony Cheung's avatar Tony Cheung

Upload New File

parent 286fc808
#include <iostream>
using namespace std;
class SmartPtr
{
int *ptr; // Actual pointer
public:
// Constructor: Refer https://www.geeksforgeeks.org/g-fact-93/
// for use of explicit keyword
explicit SmartPtr(int *p = NULL) { ptr = p; }
// Destructor
~SmartPtr() { delete(ptr); }
// Overloading dereferencing operator
int &operator *() { return *ptr; }
};
int main()
{
SmartPtr ptr(new int());
*ptr = 20;
cout << *ptr;
// We don't need to call delete ptr: when the object
// ptr goes out of scope, destructor for it is automatically
// called and destructor does delete ptr.
return 0;
}
// output
// 20
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment