Calling a method from another method in the same class in C++

Solution 1:

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;
}

Solution 2:

That's exactly what you are doing.

Solution 3:

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.

Solution 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.

Solution 5:

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()
}