In the second class, we will continue our look at C++ classes by
further developing the Rational class. We will also discuss compiling
C++ programs at UMBC.
C++ Compiling
C++ source files have a .C (upper case) extension. On some machines, you
can also use the .cpp extension.
C++ header files have a .h extension.
The C++ compiler on the SGI machines is invoked as CC, and
is very much like the usual C compiler cc.EXAMPLE: CC -o -g
produces and executable from source code (with debug information)
EXAMPLE: CC -c
produces an object (.o) file from the source code.
Rational Class Definition - First Try
#ifndef __RATIONAL_H_
#define __RATIONAL_H_
class Rational
{
private:
int num;
int den;
public: // overloaded member functions
int Num() const;
int Den() const;
void Num (const int n);
void Den (const int d) { den = d; }
};
#endif
Function OVERLOADING (more than one function with the same name)
is possible because a function's SIGNATURE includes
not only the function name, but also the number and type of the parameters.
The function's signature DOES NOT include the return type.
NOTE that in C++, function prototypes are MANDATORY.
Rational Implementation -- First Try
Recall that
Rational::Den(const int d)
was implemented in rational.h
Functions of this type -- that set or retrieve values of the
private data members -- are called "accessor" functions, since they
allow our main program to (indirectly) access our private data.
#include "rational.h"
// get the value of the numerator
int Rational::Num () const
{
return num;
}
// get the value of the denominator
int Rational::Den () const
{
return den;
}
// set the value of the numerator
void Rational::Num (const int n)
{
num = n;
}
//----------------------------------------------
main ()
{
Rational x, y;
x.Num(5);
x.Den(9);
printf ("%d / %d", x.Num(), x.Den());
}
//---------------------------------------------------------
Question -- THE FOLLOWING IS ILLEGAL... WHY?
printf ("%d / %d", x.num, x.den);
Question-- The functions were called as x.Num(). The code in main clearly
indicates that we want to access x's numerator. How does the code in the class
implementation "know" which instance (x, y, z) to access??
NOTE the use of the keyword const