Object
C vs. C++
Objects = Attributes *+ Services*
- Data: the properties or status
- Operations: the functions
Stash
Container
Container is an object that holds other objects.
- For most kinds of containers, the common interface is put() and get().
Stash is a container that stores objects and can be expanded during running.
- Each element in Stash is a clone of the object.
struct Stash {
int size; // Size of each space
int quantity; // Number of storage spaces
int next; // Next empty space
// Dynamically allocated array
unsigned char* storage;
// Functions!
void initialize(int size);
void cleanup();
int add(const void* element); void* fetch(int index);
int count();
void inflate(int increase);
};
Implementation of the functions
We just defined in the header file that there will be these functions in this struct.
All the bodies of these functions will be in a source file.
Call the functions in a struct
Objects
In C++, an object is just a variable, and the purest definition is “a region of storage”.
The struct variables mentioned before are just objects in C++.
Object vs. Class
- Objects (cat)
- Represent things, events, or concepts
- Respond to messages at run-time
- Classes (cat class)
- Define properties of instances
- Act like types in C++
OOP Characteristics
-
Everything is an object.
-
A program is a bunch of objects telling each other what to do by sending messages.
-
Each object has its own memory made up of other objects.
-
Every object has a type.
-
All objects of a particular type can receive the same messages.
Definition of a class
In C++, separated .h
and .cpp
files are used to define one class.
- Class declaration and prototypes in that class are in the header file (.h).
- All the bodies of these functions are in the source file (.cpp).
compile unit
- The compiler sees only one
.cpp
file, and generates.obj
file - The linker links all
.obj
into one executable file - To provide information about functions in other
.cpp
files, use.h
The header files
Header = interface
The header is a contract between you and the user of your code.
- Only declarations are allowed to be in .h
- extern
- variables
- function prototypes class/struct
- declaration
#include <xx>
:same as #include <xx.h>
//Standard header file structure
#ifndef HEADER_FALG
#defien HEADER_FALG
//Type declaration here ...
#endif //HEADER_FLAG
- Tips for header
- One class declaration per header file
- Associated with one source file in the same prefix of file name.
- The contents of a header file is surrounded with #ifndef #define… #endif
#pragma
once equivalent to#ifndef…#endif