Possible Duplicate:
Overloading operator ->
Hi,
I've seen that operator->()
is chained (re-applied) after it is evaluated, for example:
struct Bar
{
Bar() : m_str("Hello world!") {}
const string* operator->() const { return &m_str; }
string m_str;
};
struct Foo
{
const Bar& operator->() const { return m_bar; }
Bar m_bar;
};
int main()
{
Foo f;
cout << f->c_str() << endl;
return 0;
}
works pretty fine, which requires three operator->()
to be evaluated - Foo::operator->()
, Bar::operator->()
and regular pointer resolution.
But it wont work with pointers in the middle - if Foo::operator->()
returns pointer to Bar instead of reference, it wont compile. Same happens with auto_ptr<auto_ptr<string>>
for example.
Is it specific to non-overloaded operator->()
so it is only applied once and does not cause chaining?
Is it possible to make code below works without using (*ptr2)-> ...
?
int main()
{
string s = "Hello world";
auto_ptr<string> ptr1(&s);
auto_ptr<auto_ptr<string> > ptr2(&ptr1);
cout << ptr1->c_str() << endl; // fine
cout << ptr2->c_str() << endl; // breaks compilation
}
Thanks!