operator overloading1

Hello.
I have a class definition as follows:

1
2
3
4
5
6
7
8
9
10
class string{
       public:
              substring operator () (unsigned int start, unsigned intlength);
              istream & getline(istream &);
              char & operator [](unsigned int)const;
              operator const char* () const;
       private:
               unsigned short int bufferlength;
               char* buffer;
 };


why doesn't it err on operator const char* () const;?
conversion/cast operator.
operator const char* () const;
This declares a convesion operator of type string to type const char*.

It will run as follows.


1
2
3
4
const char* cstr;
string cppstr;

cstr= cppstr; //conversion operator string to const char* runs first, then assignment operator (none exists for const char*, a plain-old-data type) 
Last edited on
const char* is the data type of the function?

and isn't it an error that 'operator' is used alone?
const char* is the return type.

Again, you're specifying the conversion/cast operator. Technically it is a function, but it's meant to be used as a cast-converter. That's what the operator keyword specifies.
Normally you'd get an error (string to const char* conversion incompatible), but that overload took care of it.
Why won't you try making your own, custom string class and try to run my code above? You're overloading a class type here. More specifically a 'return'-type from a cast.
Last edited on
Topic archived. No new replies allowed.