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 m_real = 0.0, m_imag = 0.0;
double m_mag = 0.0, m_theta = 0.0;
bool m_cartesian, m_polar;
void calculate_cartesian ();
void calculate_polar ();
public:
complex_number () { m_cartesian = true; m_polar = false; }
complex_number (double r, double i)
{
m_real = r; m_imag = i;
m_cartesian = true; m_polar = false;
}
void print_cartesian ();
void print_polar ();
double real ();
double imag ();
double mag ();
double theta ();
void cartesian (double r, double i);
void 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!
1#include <iostream>
2#include <cmath>
3#include <cassert>
4
5class complex_number
6{
7 double m_real = 0.0, m_imag = 0.0;
8 double m_mag = 0.0, m_theta = 0.0;
9 bool m_cartesian, m_polar;
10 void calculate_cartesian ();
11 void calculate_polar ();
12
13public:
14 complex_number ();
15 complex_number (double r, double i);
16 double real ();
17 double imag ();
18 double mag ();
19 double theta ();
20 void print_cartesian ();
21 void print_polar ();
22 void polar (double m, double t);
23 void 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.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}