Search code examples
c++operator-overloadinglogarithm

Implementing Operator Overloading with Logarithms in C++


I'm having some issues with implementing a logarithm class with operator overloading in C++.

My first goal is how I would implement the changeBase method, I've been having a tough time wrapping my head around it.

I have tried to understand the math behind changing the base of a logarithm, but i haven't been able to. Can someone please explain it to me?

My second goal is to be able to perform an operation where the left operand is a double and the right operand is a logarithm object.

Here's a snippet of my log class:

// coefficient: double
// base: unsigned int
// result: double
class _log {

 double coefficient, result;
 unsigned int base;

public:

 _log() {
  base = 10;
  coefficient = 0.0;
  result = 0.0;
 }
 _log operator+ ( const double b ) const;
 _log operator* ( const double b ) const;
 _log operator- ( const double b ) const;
 _log operator/ ( const double b ) const;
 _log operator<< ( const _log &b );

 double getValue() const;

 bool changeBase( unsigned int base );
};

You guys are awesome, thank you for your time.


Solution

  • A few things

    1. Using an _ in the front of your class is a Very Bad Idea (tm). From the c++ standard:

    17.4.3.2.1 Global names [lib.global.names] Certain sets of names and function signatures are always reserved to the implementation:

    • Each name that contains a double underscore (_ _) or begins with an underscore followed by an uppercase letter (2.11) is reserved to the implementation for any use.
    • Each name that begins with an underscore is reserved to the implementation for use as a name in the global namespace.165

    165) Such names are also reserved in namespace ::std (17.4.3.1).

    1. I'm guessing that you used _log instead of log due to the clash with log() in cmath. It is a Very Bad Idea to keep your own classes in the standard namespace for this very reason. Maybe the next version of the standard will provide a _log or Logarithm class? Wrap your own class in namespace somename {} and reference it by using somename::Logarithm()

    2. As others have mentioned already You need to declare your operator overloading as friend. Instead of what you have

      log operator+ ( const double b ) const;

      change it to

      friend log operator+(const double d, const log& l);
      

      and define the function in the namespace scope.

    3. Here is the math for the change of base formula

      Change of base formula

    4. Coefficient in math means the part that is being multiplied by the log. So if you had A log_b(x) = y

      A is the coefficient, B is the base, and Y is the result (or some other names)