C++ Overview 1. // Comment style is standard ------------------------------- As mentioned, also adopted for C99. 2. void in parameter list is optional ------------------------------------- int fn(void); int fn(); I prefer to use void, but in C++, it is a matter of personal preference. 3. default arguments -------------------- int fn(int n=1) { } fn can now be called two different ways: fn(4); sets fn's n variable to 4 fn(); sets fn's n variable to the default of 2 4. reference arguments ---------------------- References are a different way of handling pointers. void fn(int& a) { a=4; } Now if we call: int y=1; fn(y); Inside fn, we change the value of y just as if it had been passed as a pointer value. 5. Function overloading ----------------------- Multiple functions with similar actions can be called the same thing: float area(float h, float w) { return(h*w); } int area(int h, int w) { return(h*w); } The compiler decides which to call based on the parameters. 6. Function templates --------------------- template T area(T h, T w) { return(h*w); } int area(int,int); float area(float, float); The function is exactly the same for both types, int and float, so C++ allows a template to be created. The individual functions are creates based on the prototypes. 7. global scope resolution -------------------------- int a; int fn(int a) { return(a * ::a); } The :: in front of the global variable name allows access to the global while the local is still accessible. 8. Classes ---------- Classes are the reason that C++ was created - allows collections of objects and methods (variables and functions) that are related. class Rectangle { Rectangle(int, int); void print(); int area(); int getH(); int getW(); void setH(int); void setW(int); private: int h; int w; }; This creates the class with several methods and two properties (h and w). Rectangle r; // creates a new rectangle object r.setH(10); r.setW(10); r.print(); // "w=1-, h=10" area = r.area(); // returns 100 r.h = 10; // illegal r.w = 10; // illegal Rectangle::Rectangle(int a=0; b=0) // constructor { h = a; // set private h to a w = b; // set private w to b } void Rectangle::print() { cout << "w=" << w << " h=" << h << endl; return; } C++ has all of the features of C, plus classes and associated technology enhancements: encapsulation (classes, public, private) inheritance (using a class to create a new class) polymorphism (changing code based on context - templates and overloading)