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


Question

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

1
30
6/11/2009 8:18:04 PM

Accepted Answer

That's exactly what you are doing.

23
6/11/2009 8:05:31 PM

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

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon