- Declaration: int x;
- Definition (of a variable): int x = 5;
- value as well as type
- definition of a pointer: int *p = new int; (sets address,
but doesn't set value at that address)
- Definition of a class:
class A { public: int f() { return 42; } };
- Can also declare classes: class A;
- Generally: declarations just say something exists
- Declaring a function: a function prototype
- double sqrt(double); // parameter name not needed
- int strlen(const char* text);
- int strcmp(const char* a, const char* b);
- char* strcpy(char* dest, const char* src);
- Defining a function:
// untested, from http://tinyurl.com/zy8scsu
#include <math.h>
double sqrt(double x) {
if (x <= 0)
return 0; // if negative number throw an exception?
int exp = 0;
x = frexp(x, &exp); // extract binary exponent from x
if (exp & 1) { // we want exponent to be even
exp--;
x *= 2;
}
double y = (1+x)/2; // first approximation
double z = 0;
while (y != z) { // yes, we CAN compare doubles here!
z = y;
y = (y + x / y) / 2;
}
return ldexp(y, exp / 2); // multiply answer by 2^(exp/2)
}
- Fundamental rule in C++: identifiers must be declared
before any references (where "before" includes "somewhere in the same
class")
- "Identifiers" includes functions, classes, structs, variables, etc.
- definitions can appear elsewhere, even in a different file
- libraries: collections of definitions with prototypes in a special file
- Separating declarations from definitions for class methods:
class ToDo {
public:
ToDo();
bool empty();
bool full();
void add(string next_item);
string next_item();
private:
string *items;
int count, capacity;
};
ToDo::ToDo() : count{0}, capacity{100}, items{new string[100]} { }
bool ToDo::empty() { return count == 0; }
void ToDo::add(string next_item) {
if ( count >= capacity ) {
string *old_items = items;
items = new string[capacity * 2];
capacity *= 2;
for(int i = 0; i < count; ++i)
items[i] = old_items[i];
delete[] old_items;
}
items[count] = next_item;
++count;
}
string ToDo::next_item() {
if ( empty() )
throw "Removing item from empty todo list.";
string result = items[0];
for(int i = 0; i < count - 1; ++i)
items[i] = items[i + 1];
--count;
return result;
}