Function Members

Steven Zeil

Last modified: Dec 26, 2016
Contents:

1 Function Members


Example: Times

struct Time {
  int hours;
  int minutes;
  int seconds;
};


void read (std::istream& in, Time& time);

void print (std::ostream& out, const Time& time);

bool noLaterThan(const Time& time1, const Time& time2);

We can move these functions inside the struct…

struct Time {
  int hours;
  int minutes;
  int seconds;

  void read (std::istream& in);

  void print (std::ostream& out);

  bool noLaterThan(const Time& time2);
};

Note that we remove a Time parameter from each function declaration.

2 Calling Member Functions

The parameter that we removed is now written to the left of the call:

Question: Where have you seen this style of call before?

Answer

3 Implementing Member Functions

printTime1.cpp
void Time::print (std::ostream& out)
{
  ⋮
}

3.1 Fully Qualified Names

A fully qualified name of a C++ entity combines the name of the specific entity with the fully qualified names of any structs/classes/namespaces that contains it.

3.2 Let’s Say That Again

After

struct Time {
   ⋮
   void print (std::ostream& out);
   ⋮
};

we might write both

void print (std::ostream& out)
{
   ⋮
}

void Time::print (std::ostream& out)
{
   ⋮
}

4 Implementing Member Functions (Cont.)

printTime2.cpp
void Time::print (std::ostream& out)
{
    if (hours < 10)
        out << '0';
    out << hours << ':';
    if (minutes < 10)
        out << '0';
    out << minutes << ':';
    if (seconds < 10)
        out << '0';
    out << seconds;
}

4.1 Implicit Access to Members

printTime2.cpp
void Time::print (std::ostream& out)
{
    if (hours < 10)
        out << '0';
    out << hours << ':';
    if (minutes < 10)
        out << '0';
    out << minutes << ':';
    if (seconds < 10)
        out << '0';
    out << seconds;
}

4.2 Multiple Struct Arguments


Example: Time with Function Members


Example: Money with Function Members