Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Need help operator overloading returning char pointer 1

Status
Not open for further replies.

DrychronRed

Programmer
Sep 15, 2002
4
US
Hi! What I have is my own variable type, CVar which, for simplicity, let's say has one member int m_nData. I need to make an operator overload that returns a string version of the variable, but returning a pointer to a local variable is a no-no (of course) but I don't want/can't alloc memory for the string before I call it due to the nature of the desired operator overload. I want to be able to do this:

CVar myvar = 10 ;
char *pString = (char *)myvar ;

which I want to result with pString containing "10"

using this method:

CVar::eek:perator (char *)
{
char strTemp[32] ;

sprintf( strTemp, "%d", m_nData ) ;

return strTemp ;
}

I know this won't work, but how else can I do it???

Thanx!!!
Cheers,

Drychron Red
 
You're right that you cannot return a local static array because it is lost upon return. You can add a static array to your class as data member but you risk expose the internal of your class, and synchronization and maintaining the integrity of the two data members becomes an issue.

Of cause, as you pointed out, if you dynamically allocate the array, the responsibility of freeing it becomes another issue.

IMHO, it might be best let the user of the class to handle the conversion. If you really wanted to do it in your class, you might want to consider to return a std::string object. Instead of writing it as a conversion operator (which unwanted implicit conversion might become a problem), you write it as a member function:
Code:
    string CVar::asString(void)
    {
        char strTemp[32] ;
        sprintf( strTemp, "%d", m_nData ) ;
        return std::string(strTemp);
    }
[\code]
To use it:
[code]
    CVar myVar = 10;
    std::string strMyVar = myVar.asString();
[\code]
HTH
Shyan
 
Thank you Shyan.

I am not familiar with std:string, but I will be soon. :)

In general, I think using a method instead of a cast is going to have to do it. It's not as pretty, but then again, neither is strcpy(), etc.

I am using this in kernel mode ring0 where there is no CString. Maybe I should make my own. Thanks!

Cheers,

Drychron Red
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top