tags:

views:

706

answers:

5

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

+5  A: 

That's exactly what you are doing.

Magnus Skog
+1  A: 

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
A: 

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.

tgamblin
+5  A: 

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
+1  A: 

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