14.10. Private functionsΒΆ

In some cases, there are member functions that are used internally by a class, but that should not be invoked by client programs. For example, calculate_polar and calculate_cartesian are used by the accessor functions, but there is probably no reason clients should call them directly (although it would not do any harm). If we wanted to protect these functions, we could declare them private the same way we do with instance variables. In that case the complete class definition for complex_number would look like:

class complex_number
{
private:
  double real = 0.0, imag = 0.0;
  double mag = 0.0, theta = 0.0;
  bool cartesian, polar;

  void calculate_cartesian ();
  void calculate_polar ();

public:
  complex_number () { cartesian = true;  polar = false; }

  complex_number (double r, double i)
  {
    real = r;  imag = i;
    cartesian = true;  polar = false;
  }

  void print_cartesian ();
  void print_polar ();

  double get_real ();
  double get_imag ();
  double get_mag ();
  double get_theta ();

  void set_cartesian (double r, double i);
  void set_polar (double m, double t);
};

The private label at the beginning is not necessary, but it is a useful reminder.

The active code below updates calculate_polar and calculate_cartesian to be private functions. Notice how we are no longer able to call calculate_cartesian in main. Feel free to modify the code and experiment around!

Example c192_fourteeneleven
 1#include <iostream>
 2#include <cmath>
 3#include <cassert>
 4
 5class complex_number
 6{
 7  double real = 0.0, imag = 0.0;
 8  double mag = 0.0, theta = 0.0;
 9  bool cartesian, polar;
10  void calculate_cartesian ();
11  void calculate_polar ();
12
13public:
14  complex_number ();
15  complex_number (double r, double i);
16  double get_real ();
17  double get_imag ();
18  double get_mag ();
19  double get_theta ();
20  void print_cartesian ();
21  void print_polar ();
22  void set_polar (double m, double t);
23  void set_cartesian (double r, double i);
24};
25
26complex_number add (complex_number& a, complex_number& b);
27complex_number subtract (complex_number& a, complex_number& b);
28complex_number mult (complex_number& a, complex_number& b);
29
30int main() {
31  complex_number c1(-4.0, 0.0);
32  c1.set_polar(4.0, 3.1415);
33  // ``calculate_cartesian`` can't be called in main because
34  // it is now a private member function
35  c1.calculate_cartesian();
36}