Professional Documents
Culture Documents
• File names:
source files: <filename>. cpp OR <filename>.C
header files: <filename>.h
More C++
• Specify the gnu C++ compiler (in your Makefile):
Marge Coahran CC = g++
Some material from:
Kip Irvine, “C++ and Object-Oriented • To include standard libraries in your code:
Programming” #include <iostream > (iostream.h gives a warning)
using namespace std;
1
Syntax (pass by reference) Why pass by reference?
• Prototype:
void swap(int & x, int & y);
• Allows the function to change parameter
values
• Function definition:
void swap(int & x, int & y) {
int temp = x; • Easier than passing and dereferencing
x = y;
y = temp; pointers, as we needed to in c
return;
}
• This is ok if the object has no data members that are • Now p1 and p2 point to a single copy of the array (danger!), and
pointers to dynamically allocated memory. But… second array is lost (memory leak!).
2
“Canonical” Classes Canonical Classes (II)
• Classes that use dynamic memory allocation class PriceList {
always need: public:
– constructor PriceList();
PriceList(const PriceList & P); // copy constructor
– destructor
~PriceList();
– copy constructor
PriceList & operator = (const PriceList & P);
– assignment operator private:
float* price_list; //points to list of prices
• These member functions make classes robust. int item_count ;
• Classes with these are called canonical classes. }