Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

methods

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

like image 668
devin Avatar asked Jun 11 '09 20:06

devin


People also ask

Can a method call another method in the same class?

Similarly another method which is Method2() is being defined with 'public' access specifier and 'void' as return type and inside that Method2() the Method1() is called. Hence, this program shows that a method can be called within another method as both of them belong to the same class.

How do you call a method from another?

In order to call Method in another Method that is contained in the same Class is pretty simple. Just call it by its name!

Can a method call another method in C#?

You can also use the instance of the class to call the public methods of other classes from another class. For example, the method FindMax belongs to the NumberManipulator class, and you can call it from another class Test.

Can you call method within method?

Java does not support “directly” nested methods. Many functional programming languages support method within method. But you can achieve nested method functionality in Java 7 or older version by define local classes, class within method so this does compile.


1 Answers

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; } 
like image 184
Eclipse Avatar answered Oct 20 '22 21:10

Eclipse