0
class one
{
      public:
             int a;
             one& fun1()
             {
                    cout<<"  Fun1  \n";
             }
             one& fun2()
             {
                    cout<<"  Fun2  \n";
             }
};

In main i am executing " object.fun1().fun2()" - it's working fine. Though my confusion is, in functions definition i am not returning anything, looks like it's returning this pointer, shouldn't this be an error?

instance
  • 1,366
  • 15
  • 23
  • 4
    It's undefined behavior. If it shaves your head, you can't complain. If you enabled your compiler warnings, it would have warned you. – Shahbaz May 22 '14 at 13:37
  • the compiler should show a warning, but it depends what flags you have got set and what compiler you are using. – sam May 22 '14 at 13:39
  • 3
    even though the function could return anything, the fact that the function is not virtual AND that you aren't accessing member field implies that you are just invoking a standard function, without memory error concerns. – akappa May 22 '14 at 13:40
  • [This answer](http://stackoverflow.com/a/3405364/1451714) actually gives a very good explanation why compilers cannot always treat this as an error. – lethal-guitar May 22 '14 at 13:48

1 Answers1

6

No, it's not. Have a look at this answer for an explanation why compilers do not emit an error by default.

Anyway, if there's no return, the function's return value will just be undefined (garbage), and when you try to read it, you get undefined behavior.

looks like it's returning this pointer

What is actually returned depends on the calling convention used for your particular compiler and platform. If, for example, return values are pushed on the stack, the value you get might actually be some (now invalid) leftover data which was pushed on the stack during execution of the cout statement. But it highly depends on very specific internals that you shouldn't need to be aware of most of the time - just remember that the return value will be garbage.

Now why are you able to do object.fun1().fun2()? As @akappa explained in the comments, your member functions are non-virtual and do not access any members, so the compiler is very likely compiling them as free functions that don't require a this pointer.

Many compilers have switches to warn you about missing returns, for example gcc has -Wreturn-type, and it's also activated if you set -Wall. Personally, I always define this warning to be treated as an error by setting -Werror=return-type. It depends on your compiler, but it should have some functionality to enable this as well.

Community
  • 1
  • 1
lethal-guitar
  • 4,438
  • 1
  • 20
  • 40