Abubakar said:
Hi,
lets say I have a class called "hashstring". I want to be able to
write the following code:
hashstring hs ( "hello world" );
char * somecharptr;
somecharptr = hs; // here the somecharptr starts pointing to "hello
world".
is it possible? How do I overload assignment operator such that I'm
able to assign my class to a pointer to char so that it works the way
I mentioned above.
You don't overload the assignment operator at all. If you could overload an
assignment operation, it'd be the assignment operator for char*, and of
course, you can't overload operators for built-in types.
Instead, you use a conversion operator
class hashstring
{
public:
hashstring(const char*) { ...}
operator const char*()
{
// return pointer to your string data
}
};
Now, there are a number of issues that you'll need to handle.
1. Can the recipient of such a pointer modify the string?
2. Do you want to return a pointer into your string class, or a pointer to a
copy?
2a. If you return a copy, who's responsbile for freeing the memory used by
that copy?
Implicit conversion operators like this are quite problematic and can very
easily lead to subtle bugs (especially if you haven't thoroughly addressed
the above). Generally it's a better idea to use an explicitly named
function instead of an implicit conversion. So, instead of the operator
above, you might use:
class hashstring
{
public:
hashstring(const char*) { ...}
char* dangerous_pointer_to_internal_buffer()
{
// return pointer into your buffer
}
// or
const char* c_str() const
{
// return read-only pointer to your internal, zero-terminated
buffer
}
};
This is the approach taken by the standard library string class, so it's a
good pattern to mimic in your own string class.
-cd