I'm trying to implement a Money class that has a representation for money (as in $13.00, $18.92, etc.) and a set of operations. Here's the header file so far:
#include <iostream>
namespace Currency {
class Money {
private:
long int total_cents = 0;
public:
Money();
Money(long int c);
Money(long int d, int c);
long int get_cents() const {return total_cents;}
//Money(float dollars); // TODO
};
std::ostream& operator<<(std::ostream& os, const Money& m);
std::istream& operator>>(std::istream& is, const Money& m);
// Returns the total number of cents in $d.c
long int to_cents(long int d, int c);
}
My issue is that I don't intend for the last helper function to be apart of the interface, so I want to define it only in the cpp file as an implementation function. I only want the constructor Money(long int, int) to call it, and the user will only ever deal with the Money class (I'm gonna add some more useful operations later), so they won't have any reason to call to_cents.
My worry is that if I declare it in the cpp file and the user creates another function with the same name in a separate file, there will be a name conflict, which will cause a linker error. But I can't think of any other way to hide to_cents from the interface, apart from putting it as a private member of Money. It wouldn't make much sense to make it a private member of Money since it doesn't read or write to any of its data members. The other alternative is to write out the function in the constructor, but I think it serves as a logically separate computation, so it should be its own function. What is the best way to go from here?
Let me know if there's anything I should elaborate on, thank you!
You can define a function local to a source file by wrapping it in an anonymous namespace:
// in your cpp file:
namespace {
long to_cents(long d, int c) {
// ...
}
}
You can also do the same thing by making it a static
function:
// in your cpp file
static long to_cents(long d, int c) {
// ...
}