OOP - Week 3, Lecture 2: Header and Source Files
Splitting a Program into Files
So far, every program was one file: the class and main together. That is fine for a short lesson, but it does not scale. A real class like Rectangle is used by many programs, and the programmers who use it do not want to read every line of its code. They only need to know what the class offers: its name, its functions, and what each function takes and returns.
C++ lets us split a class into two parts:
- The interface: what the class offers. It lists the data members and the prototype of each function (its return type, name and parameters), but not the code inside.
- The implementation: how the class does it. It is the code inside each function.
Each part goes in its own file, so the code that uses the class sees only the interface.
1. The Three Files
| File | Contains | Role |
|---|---|---|
Rectangle.h | the class definition: data members and function prototypes | the interface (a header file) |
Rectangle.cpp | the definition (the code) of every member function | the implementation (a source file) |
main.cpp | main, which uses the class | the user of the class |
A prototype is a functionβs first line followed by a semicolon, with no body: int area();. A definition has the body: int Rectangle::area() { return width * height; }.
2. The Header File
The header file holds the class, with each function reduced to its prototype:
#ifndef RECTANGLE_H
#define RECTANGLE_H
class Rectangle {
private:
int width, height;
public:
Rectangle(int w, int h); // constructor
void setWidth(int w);
void setHeight(int h);
int area();
void scale(int factor = 2); // the default value is written here only
bool isLargerThan(const Rectangle& other);
};
#endif
- The prototypes are the same as the first lines of the functions you wrote in the previous lectures, followed by
;.
Default Values Go in the Header Only
Default values are written in the prototype, in the header, and not in the source file:
// In Rectangle.h
void scale(int factor = 2); // correct
// In Rectangle.cpp
void Rectangle::scale(int factor = 2) { ... } // wrong: the default value is written twice
void Rectangle::scale(int factor) { ... } // correct
Why? Every file that uses the class must know the default values to compile a call such as r1.scale();. The compiler sees the header in every one of those files, but it compiles each .cpp file separately, so the code in Rectangle.cpp is not visible when it compiles main.cpp.
Header Guards
The three lines #ifndef RECTANGLE_H, #define RECTANGLE_H and #endif are a header guard. They make sure the compiler reads the class once in each .cpp file, even if the header is included several times. #ifndef means βif not definedβ, and lines that start with # are handled by the preprocessor before the code is compiled.
How it works:
- The first time the header is read,
RECTANGLE_His not defined yet, so the compiler continues, defines it, and reads the class. - If the header is read again,
RECTANGLE_His already defined, so the compiler skips everything up to#endif.
Why is this needed? A header can be included twice without you noticing, for example when two other headers both include Rectangle.h and a program includes both of them. Without the guard, the compiler sees the class twice and reports an error like βredefinition of βRectangleββ (the exact words depend on your compiler). Put a header guard in every header file. Use the file name in capital letters, with _ instead of the dot.
Many compilers also accept a single line,
#pragma once, at the top of the header. It does the same job as the three guard lines. The guard lines work on every compiler, so we use them in this course.
3. The Source File
The source file includes the header and defines every member function:
#include <iostream>
#include "Rectangle.h"
using namespace std;
Rectangle::Rectangle(int w, int h) {
width = 1;
height = 1;
setWidth(w);
setHeight(h);
}
int Rectangle::area() {
return width * height;
}
void Rectangle::scale(int factor) { // no default value here
setWidth(width * factor);
setHeight(height * factor);
}
The Scope Resolution Operator ::
A function defined outside the class needs a way to say which class it belongs to. That is the job of ::, the scope resolution operator you saw in Week 1. In Week 1, the name on the left of :: was a scope such as std. Here it is the class name:
int Rectangle::area() { ... } // the function area that belongs to Rectangle
Read it as βarea, from inside Rectangleβ. Because of that, the function can use width and height directly, exactly as it did inside the class.
The pattern is return-type ClassName::functionName(parameters):
| In the class (one file) | In the source file |
|---|---|
int area() { ... } | int Rectangle::area() { ... } |
Rectangle(int w, int h) { ... } | Rectangle::Rectangle(int w, int h) { ... } |
bool isLargerThan(const Rectangle& other) { ... } | bool Rectangle::isLargerThan(const Rectangle& other) { ... } |
Rectangle add(const Rectangle& other) { ... } | Rectangle Rectangle::add(const Rectangle& other) { ... } |
- A constructor has no return type, so it starts with
Rectangle::Rectangle. The first is the class, the second is the function. - A destructor is written
Rectangle::~Rectangle(). - Without
Rectangle::, you would define a different, ordinary function that has nothing to do with the class. It would not knowwidthandheight.
#include "..." or #include <...>
Use angle brackets for headers that come with C++ (<iostream>) and double quotes for your own headers ("Rectangle.h"). With quotes, the compiler looks first in the folder of the file that contains the #include, and then in the standard places. With angle brackets it looks only in the standard places.
4. Using the Class
main.cpp includes the header and uses the class. It never sees the code of the functions:
#include <iostream>
#include "Rectangle.h"
using namespace std;
int main() {
Rectangle r1(4, 3);
cout << r1.area() << endl; // 12
return 0;
}
The header tells the compiler that Rectangle exists and what its functions look like, so it can check every call in main. The code of the functions is in Rectangle.cpp.
5. Putting It Together
This is a smaller version of the Rectangle class from Lecture 1 (without the copy constructor, the destructor and isSmallerThan), split into three files. Use the tabs to switch between them. Each function is the same as before: only its place changed.
#ifndef RECTANGLE_H
#define RECTANGLE_H
class Rectangle {
private:
int width, height;
public:
Rectangle(int w, int h); // constructor
void setWidth(int w);
void setHeight(int h);
int getWidth();
int getHeight();
int area();
void print();
void scale(int factor = 2); // the default value is written here only
bool isLargerThan(const Rectangle& other);
Rectangle add(const Rectangle& other);
};
#endif#include <iostream>
#include "Rectangle.h"
using namespace std;
Rectangle::Rectangle(int w, int h) { // constructor
width = 1;
height = 1;
setWidth(w);
setHeight(h);
}
void Rectangle::setWidth(int w) {
if (w < 1) // validation
return;
width = w;
}
void Rectangle::setHeight(int h) {
if (h < 1) // validation
return;
height = h;
}
int Rectangle::getWidth() {
return width;
}
int Rectangle::getHeight() {
return height;
}
int Rectangle::area() {
return width * height;
}
void Rectangle::print() {
cout << width << " x " << height << " (area " << area() << ")" << endl;
}
void Rectangle::scale(int factor) { // no default value here
setWidth(width * factor);
setHeight(height * factor);
}
bool Rectangle::isLargerThan(const Rectangle& other) {
return width * height > other.width * other.height;
}
Rectangle Rectangle::add(const Rectangle& other) {
Rectangle result(width + other.width, height + other.height);
return result;
}#include <iostream>
#include "Rectangle.h"
using namespace std;
int main() {
Rectangle r1(4, 3);
Rectangle r2(2, 5);
r1.print(); // 4 x 3
r2.print(); // 2 x 5
if (r1.isLargerThan(r2))
cout << "r1 is larger than r2" << endl;
Rectangle r3 = r1.add(r2);
r3.print(); // 6 x 8
r1.scale(); // factor is 2
r1.print(); // after scale()
return 0;
}Click each line of output to see which line of main.cpp printed it.