Title: CS101 Slides
1Header files
Lab 9, Lab 10, Lab 11 and Assignment 2
2Header files
myArray.h
// declaration class myArray private int
data public myArray(int size) myArray()
myArray.cpp
// declaration class myArray private int
data public myArray(int size) myArray()
// implementation myArraymyArray(int size)
data new intsize myArraymyArray()
delete data
Break into 2 files
myArray.cpp
// implementation myArraymyArray(int size)
data new intsize myArraymyArray()
delete data
3Include statement
- The declarations are stored in the header file
- The header file has the same name as the original
file, but the extension is .h instead of .cpp
(eg. myArray.h) - Only the implementation code is stored in the
.cpp file. - But we still need the declarations!
- We must include the declarations in the .cpp file
4Include statement (example)
myArray.cpp
// declaration class myArray private int
data public myArray(int size) myArray()
// implementation myArraymyArray(int size)
data new intsize myArraymyArray()
delete data
myArray.cpp
include myArray.h // implementation myArraym
yArray(int size) data new intsize myArr
aymyArray() delete data
The include statement instructs the compiler to
get the declarations from the header file
5Separate file for main()
- The global functions, like main(), must go to a
separate .cpp file (eg. program.cpp) - Include myArray.h, if you want to use a myArray
object - program.cpp, myArray.cpp and myArray.h must be in
the same project!!!
// standard library file, uses lt gt include
ltiostream.hgt // user defined file, uses
include myArray.h void func(myArray ary)
cout ltlt using ary\n // do something
with ary void main() myArray ary(10)
func(ary)
program.cpp
6Include myArrya.h
myArray.h
myArray.cpp
ifndef MYARRAY_H define MYARRAY_H //
declaration class myArray private int
data public myArray(int size) myArray()
endif
include myArray.h // implementation myArraym
yArray(int size) data new intsize
myArraymyArray() delete data
myArray.h is included in program.cpp as well as
myArray.cpp, need to indicate and avoid
duplication by ifndef MYARRAY_H, define
MYARRAY_H and endif in myArray.h