devin
devin

Reputation: 6527

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

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

Upvotes: 50

Views: 115044

Answers (5)

MSalters
MSalters

Reputation: 179779

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

Upvotes: 5

Eclipse
Eclipse

Reputation: 45493

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

Upvotes: 74

Todd Gamblin
Todd Gamblin

Reputation: 59827

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.

Upvotes: 4

Tim Rupe
Tim Rupe

Reputation: 4321

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.

Upvotes: 5

ralphtheninja
ralphtheninja

Reputation: 132988

That's exactly what you are doing.

Upvotes: 32

Related Questions