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 bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

object conversion problem-->IString to char*

Status
Not open for further replies.

reageMan

Programmer
May 5, 2004
1
US


The stripped version of my IString class:

Code:
///////////////////////////////////////////////////////////////////////
// istring.hpp
///////////////////////////////////////////////////////////////////////
#include <string>
#include <istream>

using namespace std;

class IString
{
private:
string buffer;

public:

IString();
IString (char* str);
IString(const char* pChar);
operator char* ( ) const;
};



///////////////////////////////////////////////////////////////////////
// istring.cpp
///////////////////////////////////////////////////////////////////////
#include <istring.hpp>

IString::IString()
{
}

IString::IString(char * str)
{
buffer = str;
}

IString::IString(const char* pChar)
{
buffer = pChar;
}

IString::eek:perator char*() const
{
return (char *) buffer.data();
}


This is the code that calls it:

Code:
#include <iostream>
#include <fstream>
#include <istring.hpp>

using namespace std;
using std::ifstream;


int main()
{
char dbszSQL[1024];
IString theStartDate("2004-01-01-00.00.00.000000"), theEndDate("2005-01-01-00.00.00.000000");
sprintf(dbszSQL, " hello IString %s AND %s ", theStartDate, theEndDate);

cout<< dbszSQL<< endl;
cout<<theStartDate<<endl;
cout<<theEndDate<<endl;
return(0);

}

This is the output I get:

hello IString D AND 2004-01-01-00.00.00.000000

This is the output I expect:

hello IString 2004-01-01-00.00.00.000000 AND 2005-01-01-00.00.00.000000


What am I missing? I know this is possible and I don't want to cast the object or call a method that returns a char*. Your help would be greatly appreciated.

 
> return (char *) buffer.data();
I think this should be

return (char *) buffer.c_str();

If you made the function return a const char * (which is should do), then you should be able to omit the cast as well.



--
 
1. No need in three constructors, see:
Code:
class IString
{
public:
  IString(const char* cstr = 0) // 3 ctors at the cost of 1
  {
    if (cstr) buffer = cstr;
  }
  ...
};
2. No any cast in printf() family parameters (... specificator). Your sprintf tryes to print as a c-string raw IString objects from an argument stack... Use explicit conversion in that case...
3. In spirit of Salem's post: define conversion operator as:
Code:
 operator const char*() const { return buffer.c_str(); }
Remeber: it does not work in sprintf arg list - no explicit arg declarations for automatic casting...
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top