Function in a Class Declaring Another?

Hey, I just started C++, but my book doesn't cover classes very thoroughly (yep).

I want to have a class, class_1, with two functions, F_1 and F_2, with F_1 calling F_2. I know I have to declare F_2 within F_1, but I'm not sure how to. I tried doing just "int F_1(int);" like you would usually and it didn't work, and also "int class_1.F_1(int);", and it doesn't work either. I can post the actual code or error messages if that would be helpful. Thanks
^sorry, meant "int F_2(int);" and "int class_1.F_2(int);", not F_1.
Post your code, chief!
#include <iostream>

using namespace std;

class class_1{
public:
int F_1(int,int);
int F_2(int,int);
};

int class_1::F_1(int a,int b)
{
int F_2(int, int);
int z;
z=F_1(a,b);
z=z/2;
return(z);
}

int class_1::F_2(int a, int b)
{
int c;
c=a+b;
return(c);
}

int main()
{
class class_1 object;
int number;
number=object.F_1(2,4);
return(0);
}
You're calling F_1 from F_1 (not F_2 from F_1), which is a problem.

Other than that, though... if the functions are member functions (defined in the class), then you don't need to redefine them.

This will work:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class class_1{
public:
  int F_1(int,int);  // you only have to define them here
  int F_2(int,int);
};

int class_1::F_1(int a,int b)
{
   // then you can call F_2 here, no problem.
   int c = F_2(a,b);

   return c;
}

int class_1::F_2(int a, int b)
{
  // ...
  return 0;
}

int main()
{
  class class_1 object;
  int number;
  number=object.F_1(2,4);
  return(0);
}
Ok. Let's see what we have here...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
//int class_1::F_1(int a,int b)
//fix the declaration above too
double class_1::F_1(int a,int b)
{
    //int F_2(int, int);

    //this should not be here
    //you have already declared
    //F_2 above

    //make z a double
    double z;

    //z=F_1(a,b);

    //my guess is that you
    //wanted to write:

    z=F_2(a,b);

    //that's why z should be
    //a double and F_1 should
    //return a double

    z=z/2.0;
    return(z);
}

Here is a working version:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <iostream>
using namespace std;

class class_1
{
public:

    double F_1(int,int);
    int F_2(int,int);
};

double class_1::F_1(int a,int b)
{
    double z;
    z=F_2(a,b);
    z=z/2.0;

    return z;
}

int class_1::F_2(int a, int b)
{
    int c;
    c=a+b;

    return c;
}

int main()
{
    class class_1 object;

    double number;

    number=object.F_1(2,4);
    cout << number<< endl;

    number=object.F_1(3,6);
    cout << number<< endl;

    return 0;
}
Ah. Excellent, thank you =)
Topic archived. No new replies allowed.