Function Members

Steven Zeil

Last modified: Jun 25, 2014

Contents:
1. Function Members
2. Calling Member Functions
3. Implementing Member Functions

Structs can have Function Members

1. Function Members


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…


Example: Times

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


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


Implementing Member Functions


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



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.


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)
{
   ⋮
}


Implementing Member Functions


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;
}



Implicit Access to Members


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;
}



Multiple Struct Arguments


Example: Time with Function Members

members/times.h

members/times.cpp


Example: Money with Function Members

members/money.h

members/money.cpp