Hi,
I know that I can overlaod the operator >> and << and declare it as a friend function in the class for which i am overloading and then write the definition outside of the class.
But recently I was writing a string class for myself only to learn and find out that definition of overlaoding of << can also be in the class, my question is why is this working?
I can understand the first aproach I mentiond, include the friend function name in the class and define the funcion out side of the class.
But I am having problem to understand the following one: Can you please explain why is this working?
template <typename T>
struct BasicAllocator{
static T *Allocate(int size){
return (char *)malloc(sizeof(T) * size);
}
static void Deallocate(T *val){
if(val != NULL)
free(val);
}
};
template <typename T, class Allocator=BasicAllocator<T> >
class my_string{
T *c_str;
public:
my_string(): c_str(0){}
my_string(char *str){
c_str = Allocator::Allocate(strlen(str));
strcpy(c_str,str);
}
my_string(my_string &other){
if(this != &other){
Allocator::Deallocate(c_str);
}
}
~my_string(){
if(c_str != 0)
Allocator::Deallocate(c_str);
}
/*Why following function is working? if I take off the friend, its going to fail*/
friend ostream &operator<<(ostream &stream, my_string &str){
stream << str.c_str;
return stream;
}
/*I though may be I can also define the funciton in the class itself, but I can not call what() from outside, and i dont want to call it str.what()*/
friend void what(){
}
};
typedef my_string<char> SString;
if I take of the friend from infront of the method name, it fails compiling.
Thanks in advance.
Regards,
S