C++ where to write functions of a class?

Viewed 89

In my C++ project I have 2 files: trip.h trip.cpp

  1. If I want to write a helper function that takes two ints and returns the multiplication of them where should I write it and how (const, static etc...)? Note: I don't want the user to be able to use it if that is possible as in C language when we declare it as static.

  2. if a function needs to access private members we declare it as a friend inside the class. But, should I write its title again outside the class in the .h file and write its definition in the .cpp file? Note: I was asked to make it an external function which means written outside the class.

Edit: I want answers to the exact questions above, I know I can solve this by different ways as suggested but I want to stick to this method

1 Answers
  1. I would declare and implement the function in trip.cpp as a static function. C++ is backwards-compatible with C so anything from C applies. As you already know, declaring the function static limits is visibility to that object file.

  2. I would use a static private method for that class. Static here means something different than #1 - the new meaning is that it can be invoked without an association to any instances for the class it is declared under. Private meaning it can call that class's private methods (provided it has a handle to an object first). If the function is relatively short, I would just implement it in the .h file - though many prefer it in the .cpp file.

Related