Declaring/Defining Class Functions?

So you know how it's best to always try to Declare your regular functions before int main(), then define the functions at the very end of the program like:

1
2
3
4
5
6
7
8
9
10
int add(int x, int y);
int main()
{
add(5,6);
return 0;
}
int add(int x, int y)
{
return x+y;
}


Well, could you do that as well with functions of classes? Is it needed? And, if so, how would you do it? For example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class soldier
{
public:
void attack(int number);
health;
}
int main()
{
soldier Tom;
tom.attack(10);
return 0;
)
soldier::attack(int number)
{
health -= number
}


Okay, I know my code doesn't make sense but that's not the point. My question is, should we define the member functions at the end of the program like normal functions? And if so, is this the right way to do it?

Thank You!
Typically what is done is the class goes in a header, then the bodies of the member functions go in a separate cpp file.

In your case you would have this:

1
2
3
4
5
6
7
8
9
10
11
12
13
// soldier.h

#ifndef SOLDIER_H_INCLUDED
#define SOLDIER_H_INCLUDED

class soldier
{
public:
  void attack(int number);
  int health;
};

#endif 

1
2
3
4
5
6
7
8
// soldier.cpp

#include "soldier.h"

void soldier::attack(int number)
{
  health -= number;
}

1
2
3
4
5
6
7
8
9
10
// main.cpp

#include "soldier.h"

int main()
{
  soldier Tom;
  tom.attack(10);
  return 0;
}
Thanks Disch! Now I remember that from my book, except that my book didn't teach us how to combine those files, but I'll figure it out :). Thanks again, Disch !
Topic archived. No new replies allowed.