+ Reply to Thread
Results 1 to 2 of 2

Thread: How to create a class whose object must reside on heap?

  1. #1
    Junior Member
    Join Date
    Feb 2012
    Posts
    49

    How to create a class whose object must reside on heap?

    Hi all,

    How to create a class whose object must reside on heap?

    Regards.

  2. #2
    Hi,

    There is a technique which can be used to achieve this.

    Make constructor of the class private.

    Following is the example;

    Code:
    class CStudent
    {
    private:
    	CStudent() {}
    
    public:
    	static CStudent *GetPointer()
    	{
    		CStudent *pStudent =  new CStudent() ;
    
    		return pStudent ;
    	}
    } ;
    
    void UseClassUsingPouinter()
    {
    	//cannot access private member declared in class 'CStudent'
    	//CStudent objStudent ;
    
    	CStudent *pStudent = CStudent::GetPointer() ;
    
    	delete pStudent ;
    	pStudent = NULL ;
    }
    Note that you will get compile time error when you try to create a object on stack!

    Regards.

+ Reply to Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts