8

Consider the following:

class A{

    //data members

    void foo()
    {
        bar();//is this possible? or should you say this->bar() note that bar is not static
    }
    void bar()
    {

    }
}//end of class A

How do you call member functions from within another? And how does static functions affect the use of 'this'. Should functions be called on an object?

Namratha
  • 16,630
  • 27
  • 90
  • 125

2 Answers2

7

Nawaz is correct: 'this' is implicit. The one exception is if foo were a static function, because in static functions there is no 'this'. In that case, you can't use bar() unless bar() is also a static function, and you can't use this->bar() at all.

Ens
  • 106
  • 2
  • There's also weird cases where you're calling a non-static member of a base that's not automatically brought into the current scope, and you've not done it explicitly with a `using` statement, but the poster's clearly got simpler things to worry about. – Tony Delroy Feb 08 '11 at 07:59
  • @Tony: Could you please elaborate on those weird cases? – Namratha Feb 08 '11 at 08:41
  • @Namratha: I've never paid a lot of attention - it's more one of those things you just learn to recognise and fix when the compiler complains rather than remembering the exact issue, but from vague memory: if the derived class has a function named x() then templated x()s in the base class won't be brought into scope unless explicitly requested with `using`. – Tony Delroy Feb 08 '11 at 08:46
4
bar();//is this possible? or should you say this->bar()

this is implicit. So both of them are equivalent. You can use any of them. But then I think, if just bar() is enough, then why use this->bar()?

Use this only when there is some ambiguity, otherwise use the simpler one!

Nawaz
  • 353,942
  • 115
  • 666
  • 851
  • Is the function call bar() allowed if it is not a static function? Is it not necessary to call bar on an object? – Namratha Feb 08 '11 at 07:02
  • @Namratha: Are you not repeating yourself? Did I not say both of them are equivalent? Why don't you write some code and see yourself if `bar()` is getting called or not? – Nawaz Feb 08 '11 at 07:13
  • 3
    No because your answer is not clear. You haven't answered my question regarding the static keyword and when functions must be called on an object. – Namratha Feb 08 '11 at 07:40