Zak Henry
Zak Henry

Reputation: 2185

C++ classes - how to reference a member function from another member function

I'm very new to c++ classes, so this is probably a really obvious question, but because I'm not familiar with the lingo yet I cant seem to be able to get a correct search term.

Anyway, what I am trying to do is have a public function in a class access a private function in same class.

eg

//.h file:

class foo {

float useful(float, float);

public:

int bar(float);

};

//.cpp file:

int foo::useful(float a, float b){
//does something and returns an int
}

int foo::bar(float a){
//how do I access the 'useful' function in foo?? eg something like
return useful(a, 0.8); //but this doesnt compile
}

Upvotes: 0

Views: 1842

Answers (3)

Drew Hall
Drew Hall

Reputation: 29055

Since you haven't posted the error message your compiler gives you, I'll take a guess. The return types of useful() don't match in the .h and .cpp files. If you make them match (both int or both float) everything should work as you expect.

Upvotes: 0

riwalk
riwalk

Reputation: 14223

Your return types don't match:

//.h file:

class foo {

float useful(float, float);      // <--- THIS ONE IS FLOAT ....

public:

int bar(float);

};

//.cpp file:

int foo::useful(float a, float b){       // <-- ...THIS ONE IS INT. WHICH ONE?
//does something and returns an int
}

int foo::bar(float a){
//how do I access the 'useful' function in foo?? eg something like
return useful(a, 0.8); //but this doesnt compile
}

The compiler looks for a function definition that matches exactly. The compiler error that you are getting is probably complaining about the fact that it a) can't find float useful(), or b) doesn't know what you mean when you're talking about int useful.

Make sure those match, and calling useful within bar should work just fine.

Upvotes: 1

Jon
Jon

Reputation: 437376

The function useful is declared to return a float, but you define it as returning an int.

Contrast

float useful(float, float);

vs

int foo::useful(float a, float b){
    //does something and returns an int
}

If you change the declaration to int useful(float, float) and return something from the function it will work fine.

Upvotes: 2

Related Questions