3

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
    Brief question - why not add getters/setters to your class if you need access to private members? Or if needed, inheritance if it makes sense? I feel dirty every time I need to use `friend`... Declaring a header `extern "C" {}` generally will allow C access. – Michael Dorgan Jun 03 '20 at 19:08
  • @MichaelDorgan I don't want to use that, I am asking about the specific question I have above, thanks for understanding –  Jun 03 '20 at 19:37
  • So you want a way to break class data hiding to allow others to access internal data from external functions? Then why bother with C++. If you want file scope functions, declare static and don't include the prototypes in the headers. No other module will be able to see your function this way. For part 2, I'll leave it to someone else to answer as this goes against many best coding practices. Maybe you are constrained by existing, old code that you need to patch into? Having that info would help others in your next question. – Michael Dorgan Jun 03 '20 at 21:28
  • that's not what I want, I want to hide data,,, –  Jun 03 '20 at 21:40
  • 1. You can define a static function in the .cpp file (but not declare it in the .h) as in C. Another way is to use an [unnamed namespace](https://stackoverflow.com/a/18240528/4944425). 2. No, the declaration inside the class is enough. Consider using a free function (not friend) and adding some accessors to your class, instead. https://wandbox.org/permlink/kcHUjuY6TOWeCFvV – Bob__ Jun 03 '20 at 21:46

1 Answers1

-1
  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.