3. 3
The Multiple-FileApproach
• Haveeach major classasaseparate program
• Re-use:Theclasscanthen be used by other programs using the #include
macro instead of the copy-&-pasteapproach
• Put the class/function declarations in a header (.h) file, and the
class/function implementations in another (.c or .cpp) file. This
achieves data hiding.
4. 4
Example
class Stack{
public:
typedef int dtype;
Stack(int cap=100);
int getCapacity();
void push(dtypeb);
dtype pop();
dtype peek();
bool isEmpty();
private:
dtype *dataptr;
int top;
int capacity;
};
#include"Stack.h"
Stack::Stack(intcap){
top=0;
capacity =(cap>0)?cap:100;
dataptr =newint[capacity];
};
int Stack::getCapacity( ) {
return capacity;
};
int Stack::dtype Stack::pop(){
assert(!isEmpty());
returndataptr[--top];
};
// the implementation of
// the remaining methods
........
#include <cstdlib>
#include<iostream>
#include"Stack.h”
using namespacestd;
// local stuff,ifany
int main(intargc,
char*argv[]){
………
}
Stack.hfile: Stack.cpp file: Project1.cpp file:
5. 5
What should Go intoa .hFile
• Only declarations (i.e., info to thecompiler)
• Nothing that requiresstorage
• Reason:
• aheader file gets included in several files ofaproject;
• if storage for avariable (or for acode) is allocated multiple times, you get a
multiple-definition compilation error
• Advanced: Oneexception to this rule is static data (data local to a
file), becausethe linker does not allocate multiple instances tostatic
data.
6. 6
RedeclarationsIssues
• An X.hfile canhave: #include “Y.h”
• Consider this scenario:
• TheX.hfile has:
#include “Y.h”
#include “Z.h”
• TheY
.hfile has: #include“Z.h”
• Thismeans: the declarations in Z.hare includedtwice
in X.h.Thesecond declarations are called
redeclarations
• Classredeclarations are not allowed.
• So,we have a problem
7. 7
Redeclarations Issue Solution
• Inside each Z.hfile, do:
• Add to at the start of the file (right after all the #includes)the next two lines:
#ifndefZ_H_ // Not that Zis the name of .h file
#defineZ_H_
• Add the following line at the very end of Z.h(on aseparate line):
#enddef