50

I wrote a method (that works fine) for a() in a class. I want to write another method in that class that calls the first method so:

void A::a() {
  do_stuff;
}

void A::b() {
  a();
  do_stuff;
}

I suppose I could just rewrite b() so b(A obj) but I don't want to. In java can you do something like this.a().

I want to do obj.b() where obj.a() would be called as a result of obj.b().

sth
  • 222,467
  • 53
  • 283
  • 367
devin
  • 6,407
  • 14
  • 48
  • 53

5 Answers5

71

What you have should work fine. You can use "this" if you want to:

void A::b() {
  this->a();
  do_stuff;
}

or

void A::b() {
  this->A::a();
  do_stuff;
}

or

void A::b() {
  A::a();
  do_stuff;
}

but what you have should also work:

void A::b() {
  a();
  do_stuff;
}
Eclipse
  • 44,851
  • 20
  • 112
  • 171
32

That's exactly what you are doing.

rtn
  • 127,556
  • 20
  • 111
  • 121
  • 9
    The answer ^^^ here is not useful; the one below with +44 points is a LOT more insightful. I recommend to change the order in the long run. I will explain why: I came to this here via Google, and the answer was not helping me - but the answer below WITH the syntax made me realize that I simply forgot a (). So the answer below with the +44 points was more helpful for my case, whereas the "what you are doing" comment adds really almost nothing at all to it. – shevy May 05 '20 at 22:13
5

It looks like the code you wrote in your block would work just fine. Just make sure you have both the a() and b() methods defined inside your class properly.

Tim Rupe
  • 4,323
  • 1
  • 22
  • 23
4

What you have written there should work fine. In C++ if you call a within b and both are instance methods of some class A, then you don't need to qualify it. Both a and b are in each others' scope.

Todd Gamblin
  • 58,354
  • 15
  • 89
  • 96
4

There's one case in which you might have slightly unexpected results. That is if A::a() is virtual, obj actually has type DerivedFromA, and DerivedFromA::a overrides A::a. In that case, the simple call a(); or the more verbose this->a(); will not call A::a but DerivedFromA::a().

Now, this is probably intended, since class A declared a() to be virtual. But if you really don't mean it, you can ignore the virtual by writing the call either as

void A::b()
{
    A::a(); // or
    this->A::a(); //Both ignore the virtual-ness of a()
}    
MSalters
  • 173,980
  • 10
  • 155
  • 350