#include <iostream>
#include <cstring>
using namespace std;

class String
{
    private:
        char *ptr;
    public:
        String();
        String(char* s);
        ~String();

        operator char*() { return ptr; }
        int operator==(const String &other);
};

int main()
{
    String a("STRING 1");
    String b("STRING 2");

    cout << "The value of a is: " << endl;
    cout << a << endl;
    cout << "The value of b is: " << endl;
    cout << b << endl;

    return 0;
}

String::String()
{
    ptr = new char[1];
    ptr[0] = '\0';
}

String::String(char* s)
{
    int n = strlen(s);
    ptr = new char[n + 1];
    strcpy(ptr, s);
}

String::~String()
{
    delete [] ptr;
}

int String::operator==(const String &other)
{
    return (strcmp(ptr, other.ptr) == 0);
}

In the program above I have a few questions.
My C++ book says that this line operator char*() { return ptr; } is what allows an object of this clas to be used with the stream operators << & >>. How is this since neither << nor >> are anywhere in that line as in other operator methods? Also, how is it that this operator does not show a return type before the method name, it just says operator?
My second questions is this line return (strcmp(ptr, other.ptr) == 0); these short hand line have always confused me. I believe this to be. if(strcmp(ptr, other.ptr) == ture) return 0; is that understanding correct?

the >> and << operators are overloaded for char*. Since you have an operator char* defined for you class it is implicitly convertable into a char*. Since it is implicitly convertable you can use it with the default stream operators.

For your second question strcmp() reutrns an integer depending on how the string compare:

int strcmp ( const char * str1, const char * str2 );

Returns an integral value indicating the relationship between the strings:

<0   the first character that does not match has a lower value in ptr1 than in ptr2
0   the contents of both strings are equal`
>0  the first character that does not match has a greater value in ptr1 than in ptr2

so return (strcmp(ptr, other.ptr) == 0); says return the return of strcmp(ptr, other.ptr) comapred to 0. So if the strings are equal then strcmp(ptr, other.ptr) will return 0 and 0 == 0 is true so the return becomes return true;. if the strings are not equal it will return false.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.