member and non member functions

Hi, I am learning about classes and read that a header file should contain non member function declarations, and the cpp file should contain member function declarations. What is the difference between non member and member, ive tried searching it, but a lot of the explanations were too complicated for me to understand. If someone could maybe explain it simply, or maybe with an example, it would be very helpful. Thanks
That’s not quite right, and part of it is vocabulary.

First: member vs nonmember:

A member function is a function that is part of a class.
A non-member function is one that is not part of a class.

1
2
3
4
5
6
class Quux
{
  void do_something();  // this function is a member of the Quux type
};

void do_something_else();  // this function is NOT a member of any structured type 


Second: declarations and definitions:

A declaration says that something exists.
A definition says what that something is.

Declarations belong in header files (so that other parts of the program know what exists).
Definitions belong in cpp files.

Hence, if I were to write a function (by defining it)

1
2
3
4
5
6
// this is my cpp file

double distance( double a, double b )
{
  return sqrt( a*a + b*b );
}

And I wanted to be able to use that function in multiple cpp files, I would have to create a header with a declaration of what that function looks like to be used:

1
2
3
// this is my header file

double distance( double, double );


The same holds true for classes:

1
2
3
4
5
6
7
8
9
// this is my header file.
// it declares the class and its (only) member function:

struct point
{
  double x, y;

  double slope() const;
};

1
2
3
4
5
6
// this is my cpp file, defining the member function

double point::slope() const
{
  return y / x;
}

For really simple member functions, you can just define them along with the class declaration as well:

1
2
3
4
5
6
7
8
struct point
{
  double x, y;
  double slope() const
  {
    return y / x;
  }
};


Now that that is straight, time to mess with your brain. Remember that a declaration only tells what is necessary to use a thing. A definition tells everything about that thing. Because it is required to know everything about a class’s structure to use it, in header files you do technically define a class — it is both declared and defined. So the terms wind-up getting used pretty interchangeably when it comes to classes.

1
2
3
4
5
6
7
8
struct Student
{
  string ID;
  string surname;
  string given_names;
  vector <int> grades;
  double grade() const;
};

Student is both declared and defined sufficient to use it. (Its member function, however, is only declared... LOL.)

Hope this helps.
The headaches mean your brain is learning stuff.
Topic archived. No new replies allowed.