Make an Object Appear Like a Pointer

You can make an object appear like a pointer with a smart pointer. If a class overloads the operator ->( ), then any object of that class can appear like a pointer when the operator ->( ) is called. The following program illustrates this:

#include "iostream.h"class test{public :void fun( ){cout << "fun of smart pointer" ;}} ;class smartpointer{test t ;public :test* operator ->( ){return &t ;}} ;void main( ){smartpointer sp ;sp -> fun( ) ;}

The beauty of overloading operator ->( ) is that even though sp is an object, you can make it work like a pointer. The operator ->( ) returns the address of the object of the type test. Using this address of the test object the function fun( ) of the class test gets called. Thus even though fun( ) is not a member of smartpointer class, you can still call it using sp.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin


Recent Articles: