Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 250
  • Last Modified:

Pointer Problem

Could anyone tell me why the following code does not work?


#include "stdafx.h"

class TestClass : public CObject
{
private:
      CString fname;
      CString lname;

public:
      TestClass(LPCTSTR first, LPCTSTR last);
      CString getFirstName();
      CString getLastName();
};


TestClass::TestClass(LPCTSTR first, LPCTSTR last)
{
fname=first;
lname=last;
}

CString TestClass::getFirstName()
{
return fname;
}

CString TestClass::getLastName()
{
return lname;
}

TestClass* createObject()
{
TestClass t("ABC", "DEF");

return &t;
}



int _tmain(int argc, _TCHAR* argv[])
{
TestClass *tth=NULL;
tth=createObject();//Gives Error
CString test_cstr=tth->getLastName();      

      return 0;
}

0
csound
Asked:
csound
  • 3
2 Solutions
 
AndyAinscowCommented:
TestClass* createObject()
{
TestClass t("ABC", "DEF");

return &t;
}

t goes out of scope and is destroyed.


TestClass* createObject()
{
TestClass* t = new TestClass("ABC", "DEF");

return t;
}

don't forget you need to use delete on the returned pointer when no longer required.
0
 
nafis_devlprCommented:
I agree with Andy. But you can use auto_ptr rather than using new and delete. auto_ptr will be automatically deleted when it is not in use anymore. For using auto_ptr you have to add the two lines at the top of your source file

#include <memory>  
using std::auto_ptr; // auto_ptr class definition

TestClass* createObject()
{
     auto_ptr< TestClass > t( new TestClass("ABC", "DEF") );
     return t;
}

Nafis
0
 
AndyAinscowCommented:
To be honest I am not a fan of the garbage collection or mechanisms like that.
If I have a memory leak then it means I have made a mistake in the logic/coding.  Anything that automatically cleans up will hide coding mistakes like that from the programmer.
0
 
AndyAinscowCommented:
My comment pointer out what was going wrong and how to correct it.
0
 
csoundAuthor Commented:
Thank you for your help!=)
0

Featured Post

New feature and membership benefit!

New feature! Upgrade and increase expert visibility of your issues with Priority Questions.

  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now