Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Confused == operator

Status
Not open for further replies.

RichardF

Programmer
Oct 9, 2000
239
GB
Pop quiz:

Code:
class MyStr
{
public:
	MyStr(const char* newValue):s(newValue)
	{
	}

	operator const char*()
	{
		return s.c_str();
	}

	bool operator == (MyStr& rhs)
	{
		return rhs.s == s;
	}

private:
	std::string s;
};

int APIENTRY _tWinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPTSTR    lpCmdLine,
                     int       nCmdShow)
{
	MyStr a("hello"), b("hello");

	BOOL result_1 = (a == b);

	BOOL result_2 = (MyStr("hello") == MyStr("hello"));

	return 0;
};


When run result_1 is true, but the result_2 is false. Can anyone explain why this is ?


Regards,
Rich.
 
Because you're just comparing raw pointers as returned by calling c_str() for each object you created.

Code:
#include <iostream>
#include <string>
using namespace std;

class MyStr
{
public:
    MyStr(const char* newValue):s(newValue)
    {
      cout << "ctor called -" << s << "-" << this << endl;
    }
    ~MyStr()
    {
      cout << "dtor called -" << s << "-" << this << endl;
    }

    operator const char*()
    {
        const char *result = s.c_str();
        char *cp = const_cast<char*>(result);
        void *vp = reinterpret_cast<void*>(cp);
        cout << "() called, returning " << vp << endl;
        return result;
    }

    bool operator == (MyStr& rhs)
    {
        cout << "== called -" << s << "- -" << rhs.s << "-" << endl;
        return rhs.s == s;
    }

private:
    std::string s;
};

int  main ( )
{
    MyStr a("hello"), b("hello");

    cout << "Compare 1" << endl;
    bool result_1 = (a == b);

    cout << "Compare 2" << endl;
    bool result_2 = (MyStr("hello") == MyStr("hello"));
    cout << result_1 << " " << result_2 << endl;
    return 0;
}
[tt]
ctor called -hello-0x22eea0
ctor called -hello-0x22ee90
Compare 1
== called -hello- -hello-
Compare 2
ctor called -hello-0x22ee80
() called, returning 0x4a06ec
ctor called -hello-0x22ee70
() called, returning 0x4a0704
dtor called -hello-0x22ee70
dtor called -hello-0x22ee80
1 0
dtor called -hello-0x22ee90
dtor called -hello-0x22eea0[/tt]

--
 
Hi,

Ok I understand that the two pointers are being compared. What I dont understand is why ....

Code:
bool result_2 = (MyStr("hello") == MyStr("hello"));

Why does MyStr("hello") call into operator const char*() and not operator == (MyStr& )

Regards,
Rich
 
Shouldn't
Code:
 bool operator == (MyStr& rhs)
be
Code:
bool operator == (const MyStr& rhs) const
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top