class substr {
public:
substr(const char *s,const char p);
~substr();
friend ostream & operator<<(ostream &, substr&);
private:
char *s;
};
substr::substr(const char *str, const char p)
{
s= new char [strlen(str)+1];
if((j=strchr(str,p)) == NULL) {
strcpy(s,"--"); // copy two dashes
}
else {
strcpy(s,j); // copy the rest of the string
}
} // substr constructor
substr::~substr() { delete [] s ;} // destructor
ostream&
operator<<(ostream& os, substr& str)
{
return os << str.s;
} // operator<<
main()
{
char *string="this string has M in the middle";
cout << substr(string,'M') << endl;
} // main
This works because the first << operator looks like the function call <<(cout,substr(string,'M')). This runs the substr constructor, returning a reference to a temporary substr instance. This is passed to the operator<< function which prints the substring. The destructor is called after the psuedo-function call is completed and the temporary instance and the memory allocated for it go away.