SoftOver
 
Recommended


User login


 

Pointless Conversion

   

What will be printed? Why?

#include <iostream>

struct E
{
  void Do() {std::cout << "E Done" << std::endl;}
};
struct D
{
  void Do() {std::cout << "D Done" << std::endl;}
  E* operator->() {return &e;}
  E e;
};
struct C
{
  void Do() {std::cout << "C Done" << std::endl;}
  D* operator->() {return &d;}
  D d;
};
struct B
{
  void Do() {std::cout << "B Done" << std::endl;}
  C& operator->() {return c;}
  C c;
};
struct A
{
  void Do() {std::cout << "A Done" << std::endl;}
  B& operator->() {return b;}
  B b;
};

int main()
{
  A a;
  a->Do();
}

Explanation:

operator-> in C++ is "everfolding" - if the returned value has a class type and this class also has operator-> - it is aplied again (and again, and again) - until the returned value is not a class; in this case - pointer to D in C::operator->(). Than D::Do() is called.