C++ Language - Quick Guide
© Lubos Jules Stary,  03/29/2002
CONTENTS
Conventions	III
Recommended Books and Internet Links	III
Writing Style	1
Comments	1
Names Style	1
Program Style	1
C++ Additions - Operators and Variable Types	2
Operators	2
Variable Types - BOOL	2
Functions	2
Function DECLARATION (Forward Prototyping)	2
Default Parameters	3
Function OVERLOADING (Polymorphism)	3
Classes	3
Encapsulation, Member, Method	3
Object, Instance, Client	4
Member Access	4
Data Access - PUBLIC / PRIVATE	4
Implementing Class Methods	5
CONSTRUCTOR and DESTRUCTOR	5
Automatic Calling of a Constructor and Destructor	5
CONST Member Functions	6
INLINE Implementation	6
Class as a Member	6
Pointers	7
NEW	7
DELETE	7
Pointers Safety	7
Pointer - Automatic Calling of a Constructor and Destructor	7
Pointer - Class Member Access	8
Pointers as the Class Members	8
THIS Pointer	8
CONST Pointers	8
References	9
Passing Function Arguments by Reference	9
Passing by Reference for Efficiency	10
Pointer and References Pitfalls	10
Advanced Functions	11
Overloading Constructors	11
INITIALIZATION Stage of Constructors	11
COPY Constructor	11
OPERATOR Overloading	12
Postfix Operator Overloading	12
+ (addition) Operator Overloading	13
Operator Overloading Appendix	13
CONVERSION Operators	13
Arrays	14
Array of Objects	14
Arrays and Pointers	14
Array of Pointers to Object	15
Pointer to Array of Objects	15
STRING class	15
DERIVATION (INHERITANCE)	17
OVERRIDING Functions	19
VIRTUAL Functions	19
Special Classes and Functions	21
Abstract Data Types	21
Pure Virtual Functions	22
STATIC Member Data	22
Static Member Functions	23
Pointers to Member Functions	23
Advanced Inheritance	24
Multiple Inheritance (Derivation)	24
Virtual Inheritance	25
Containment, Delegation	26
Private Derivation	26
FRIEND Classes	27
Friend Functions	28
Streams	28
IOSTREAM Class Hierarchy Diagram	29
TEXT - Formatting (IOS)	29
TEXT - INPUT (ISTREAM)	30
TEXT - OUTPUT (OSTREAM)	30
FILE - Base (FSTREAM)	31
FILE - Status Tests (IOS)	31
FILE - Basic Manipulating (FSTREAM)	31
FILE - BINARY - INPUT/OUTPUT (ISTREAM/OSTREAM)	32
FILE - BINARY - File Pointer Moving (ISTREAM/OSTREAM)	33
Exceptions Handling	34
TRY, CATCH, THROW	34
Data Transfer	34
Specialities	35
Templates - Basic	35
Templates - Function	36
ASSERT - Macro for Debugging	37
Linked List	37
Casting Down - Dynamic_cast	38
Modular Programming	39
C++ overview	41
Functions (Methods) Declaration Overview	41
Operators Overloading Overview	41
Pointers, References, Arrays Overview	41
Derivation (Inheritance) Overview	42
Controlling Access to Class Members - PRIVATE, PROTECTED, PUBLIC	43
Specialities Overview	43
Class Declaration Overview	44
C overview	45
VARIABLES	45
OPERATORS	46
STATEMENTS	48
ADVANCED DATA TYPES	48
Pointers and Memory Representation	49
PRINTF - Formatting	51
Escape Sequences	52
GLOSSARY	53
INDEX	56

Conventions
Font	Represents
CAPITALS	C++ language key words.
courier	A program code.
bold	A new term or important thing.

Mark	Represents
NOTE:	Something important but not critically dangerous.
ATTENTION:	Very important, dangerous, can lead to a program crash.
Recommended Books and Internet Links
Jesse Liberty - Sams Teach Yourself C++ in 21 Days (online book: http://www.informit.com )
Ivor Horton - Beginning Visual C++ 6 (OOP - Object Oriented Programming + Developer environment)
Meyers, Scott. Effective C++. Addison-Wesley Publishing, 1993.
Andrew Koenig, Barbara E. Moo - Accelerated C++: Practical Programming by Example (OOP only)
Stephen Prata - The Waite Group's C++ Primer Plus (OOP only)
Stroustrup - Programming in C (OOP only)
Stanley Lippman - C++ Primer (OOP only)

© 2002, Lubos Jules Stary

Writing Style
Comments
The C++ comments are started with symbols "//" (// comment) ,  without the end symbol.
Names Style
This is a non-classic style - more usual in C++:
Variable and function names:
int boxPointGroup; // the camel notation - separate words by capitals (nameNameName)
OpenFile();   // FUNCTION name == verb (open, close, find ...)
fileState;    // VARIABLE name == noun (count, state, size ...)
fileIsOpened; // BOOLEAN VARIABLE == logical conclusion
Constant names - all capital:
enum{MAXARRAY=100};  // the constant for a part of a program
#define MAXARRAY 100 // the constant for the whole program
Function and class names should begin with a capitalized letter:
class String ...
int StrLength();
Class members and local variables should start with a lowercase letter:
int itsPoint; // itsPoint == member variable
Enumerated constants should begin with a few lowercase letters as an abbreviation for the enum:
enum TextStyle{tsBold,tsItalic,tsUnderscore};
Pointers and references:
int * pVar;    // pointer variable
int & rVar;    // reference
Spaces
Binary operators should have spaces on both sides:
x = x + 3;
Parentheses should not have spaces on either side:
AnimalArray[x].SetWeight(x+20);
Keywords, such as if, should be set off by a space
if (a == b)
Program Style
The program header:
//-----------------------------------------------------
// CPP01 - CPP language learning - basic operations 
//
//     Project:     SpaceShuttle
//     Description: print out/in, function call
//     Author:      John Megawatt
//     Last change: 14.11.2001
//-----------------------------------------------------

A function header:
//********************************
// Add - addition of two numbers
//     x: 1..200
//     y: 1..300 
//********************************
int Add(int x, int y);
The indentation style -  aligning the braces under the expression start, 4 spaces indenting the statements:
if (expression)
{
    statements;
}
The next possible separators:
//=== FUNCTIONS DEFINITIONS ========================================

//-------------------
// COUT / CIN tests
//-------------------
White space - a character that is ignored by compiler -- space, tab, new line.
Try to keep your functions short enough to print the entire function on one page. 
C++ Additions - Operators and Variable Types
Operators

Operator	Meaning	
<<	insertion - insert data to the stream	
>>	extraction - extract data from the stream	
Variable Types - BOOL

Type Name	Bytes	Range of Values	
bool	1	true / false (1 / 0)	
Functions
Parameter - a name in a function definition (the parameter is the local variable).
Argument - a value in a function calling.
Parameters passed by value - the value in the argument is copied to an internal variable (located in the stack). Changing of the parameter inside of the function, doesn't have effect on the argument variable.
Parameters passed by address - the memory address of the argument is copied to an internal variable == pointer. Changing of the parameter change directly the argument variable.
Function DECLARATION (Forward Prototyping)
Declaration - you can declare a prototype of a function (function header) before a basic definition - for example because of cross calling. You can declare the parameters without names.
Definition - full definition of the function with the body.
float findaverage(float a, float b); // DECLARATION = forward prototyping
float findaverage(float,   float  ); // LEGAL DECLARATION too

float findaverage(float a, float b)  // DEFINITION - you define the body
{
	...
}
Default Parameters
You can initialize a parameter of a function with a default value.
long MyFunction (int x = 50);
If the function calling won't include the parameter, the compiler will fill x with the default value. 
ATTENTION: If any of the parameters does not have a default value, no previous parameter (left) may have a default value.
long MyFunction(int Param1, int Param2=1, int Param3);  // INVALID!
long MyFunction(int Param1, int Param2=1, int Param3=4);  // valid
Variable Number of Parameters
after that you can call the function:
MyFunction(10);
Function OVERLOADING (Polymorphism)
Overloading - you can create more than one function with the same name. The functions must differ in their parameter list, with a different type of parameter, a different number of parameters, or both. The return type can be the same or different.
int  OverLoad(int x, int y, int z);
char OverLoad(int x, int y, int z);  // INVALID!

int  OverLoad(int x, int y, int z);
char OverLoad(int x, int y);         // VALID

int  OverLoad(int x, int y, int z);
int  OverLoad(int x, int y, long z); // VALID
Function calling - right one will be called by matching the parameters used.
void OverLoad(int x, int y);  // fun 1
void OverLoad(int x, long y); // fun 2

int int1,int2;
long long1;

OverLoad(int1,int2);  // fun 1 is calling
OverLoad(int1,long1); // fun 2 is calling
Classes
Encapsulation, Member, Method
Class -  is a collection of variables, combined with a set of related functions.
Encapsulation - data (variables) and functions are collected to one object.
Member - a variable or a function defined as a part of a class. 
The variable is called as the member variable, or the data member.
Method - a function in the class is called as a member function, or a method.

A class declaration:
class Cat // CLASS == TYPE
{
    int catAge;     // data member
    void Meow(void);         // method
};

Cat Frisky; // OBJECT == VARIABLE
Object, Instance, Client
Size of a class - is a sum of the data members sizes. Methods take up no room.
Class (is equal to type) - it takes up no room in the memory.
Object (is equal to variable) - it takes up room in the memory.
Instance - an object is an individual instance of a class. 
Client of your class - the parts of the program that use the class.
Member Access
Data member:
Frisky.catAge=5;
Method:
Frisky.Meow();
Data Access - PUBLIC / PRIVATE
All members of a class - data and methods - are private by default. 
Private - private members can be accessed only within methods of the class itself. 
Public - public members can be accessed from outside of the class.
Frisky.catAge=5; // Error - the data member is private by default
Frisky.Meow();   // Error - the method is private by default

class Cat
{
public:  // Public members
    int catAge;
    void Meow(void);
};

Frisky.catAge=5; // O.K.
Frisky.Meow();   // O.K.
As a general rule of design, you should keep the member data of a class private. 
Public accessor method - is a class member function used to read and to set the value of a private class member variable.
Accessor functions enable you to separate the details of how the data is stored from how it is used.
class Cat
{
public:  // Public members
    int GetAge();     // Public accessors
    void SetAge(int Age);
    void Meow(void);           // Public member function
private:  // Private members
    int catAge;
};

Frisky.SetAge(5); // set Frisky.catAge=5 through the public accessor
Implementing Class Methods
Implementation - the function definition (function body).
return_value  class_name::method_name(parameters)
This way defined method has the direct access to a private data of the class.
Example:
// SetAge - set a cat age
void Cat::SetAge(int age)  // method SetAge is a member of the class Cat
{
    catAge=age;   // direct access to private data
}
CONSTRUCTOR and DESTRUCTOR
Constructor - a special member method for data members initializating and memory allocating..
The constructor can take parameters as needed, but it has no return value. Name is the same as the class name.
Destructor - a special member method for data cleaning and memory deallocating.
The destructor takes no parameters and has no return value. His name is composed by "~"+class_name.
NOTE: You can't initialize class data members to the default value directly, you will have to do it through a constructor.
Default Constructors and Destructors
If you don't declare a constructor or a destructor, the compiler makes one for you. The default constructor and destructor take no arguments and do nothing.
Every class object definition calls a constructor.
Cat Frisky; // calls constructor Cat()
You can write your own constructor and destructor.
class Cat
{
public:  // Public members
    Cat(int initAge); // constructor - mustn't have a return type!
    ~Cat();           // destructor - mustn't have a return type!
    ...
};

Cat Frisky(5); // instance (object) definition + constructor with
   parameters

// Cat - constructor
Cat::Cat(int initAge) // mustn't have a return type!
{
   catAge=initAge; 
}

// ~Cat - destructor
Cat::~Cat() // mustn't be a return type!
{
   
}
A good habit is to write also a destructor, even if it does nothing.
Automatic Calling of a Constructor and Destructor
A constructor is automatically called by an object definition:
Cat Frisky; // calls constructor Cat()
The destructor is automatically called by the object termination - end of scope.
The object termination occurs by function end or by program end (end of function main() ):

void FunName()
{
    Cat Frisky;//Frisky definition-constructor is called-start Frisky scope

} // end of function - destructor is called - end Frisky scope
CONST Member Functions
If you declare a class function const, you are promising that the function won't change the value of any of the members of the class.
int GetAge() const; // GetAge() won't be able to change data
NOTE: Use const whenever possible. Let the compiler to catch your errors.
INLINE Implementation
The inline function definition causes that the compiler includes the function content (all code) instead of function calling. The resultant code is faster, but bigger. This is meaningful by very short functions, functions called only once and when you need the maximum speed of the program.
Inline implementation:
inline int Cat::GetAge() const
{
   return(catAge); 
}
When you put the definition of a function into the declaration of the class, it automatically makes that function inline:
class Cat
{
public: 
    int GetAge() const  
        { return(catAge); }  // GetAge - obtain a cat age--inline function
    ...
};
NOTE: There is no semicolon after the parentheses!
Class as a Member
You can build up a simply class and use it as the data member type in the declaration of the more complicated class.
// POINT - holds the X, Y co-ordinates
class Point     
{
public:
    void SetX(int x) { pointX = x; }
    void SetY(int y) { pointY = y; }
    int GetX() const { return pointX; }
    int GetY() const { return pointY; }
private:
    int pointX;
    int pointY;
};

// LINE - consist of two POINTS, each point with X, Y
class Line
{
public:
    Line(int X1, int Y1, int X2, int Y2); // constructor
    ~Line() {}                            // blank destructor

    Point GetPoint1() const { return linePoint1; }
    Point GetPoint2() const { return linePoint2; }
    void SetPoint1(Point Point1) { linePoint1 = Point1; }
    void SetPoint2(Point Point2) { linePoint2 = Point2; }
    float LineLength() const;
private:
    Point linePoint1;
    Point linePoint2;
};

NOTE: A structure (struct) is exactly like a class, except that its members are public by default.
Pointers
Null pointer - pointer == 0000:0000
Wild pointer - not initialized pointer.
Stray pointer / dangling pointer - using pointer without assigned memory -- after delete.
Memory leak - the pointer went out of scope, but the memory wasn't freed. You have occupied memory without any pointer.
NEW
The new operator allocates a part of memory of the defined size. The parameter is a variable_type which is the  size information for the compiler.
variable_type * pointer_variable = new variable_type;

Cat * pFrisky = new Cat; // memory space allocation (sizeof(Cat))
				     // default CONSTRUCTOR call

if (pFrisky==NULL)      // successful memory allocation test
    cout << "Not enough memory!" << endl;
When your constructor has parameters, you have to put it there:
Cat * pJoy = new Cat(5);  // memory alloc + call constructor with init
ATTENTION: When there is not enough memory, the new operator returns the NULL (== 0) pointer!
DELETE
The delete operator frees the allocated memory.
delete pointer_variable;

delete pFrisky;   // memory freeing + destructor call
pFrisky=NULL;     // clean the pointer

delete pFrisky;   // NULL pointer freeing is safe
ATTENTION: When you call delete operator on freed pointer (or not initialized), your program will crash! Therefore when you delete a pointer, set it to zero (NULL). Calling delete on a null pointer is guaranteed to be safe.
Pointers Safety
•	Check the new statement for the NULL return value.
•	Balance all new statements with a delete statement.
•	Assign NULL (==0) to all pointers that you call delete on.
Pointer - Automatic Calling of a Constructor and Destructor
A constructor is automatically called by memory allocation for an object:
Cat * pFrisky;  // pointer definition - NO Constructor called

pFrisky = new Cat;  // pointer init - memory alloc - Constructor called
A destructor is automatically called by an object termination - memory freeing:
delete pFrisky;  // memory freeing - Destructor called
Pointer - Class Member Access
The conventional (oldfashion) way - through the dot (.) operator
(*pFrisky).GetAge(); 
The modern way - through the (->) operator:
pFrisky->GetAge(); 
Pointers as the Class Members
Memory can be allocated in a class constructor, and it can be deleted in its destructor.
class Cat
{
public:
    Cat();  // constructor
    ~Cat(); // destructor 
private:
    int * pcatAge;
};

//=== IMPLEMENTATION ============================================
Cat::Cat()
{
    pcatAge=new int(10); // memory alloc + init variable - *pcatAge==10
}

Cat::~Cat()
{
    delete pcatAge; // memory dealloc
}
THIS Pointer
Every class member function has a hidden parameter: the this pointer. this points to the individual object - the instance of the class (also when the object isn't created by new). 
class Cat
{
public:
    ...
    int GetAge() const { return this->catAge; }
    // equal to: int GetAge() const { return catAge; }
private:
    int catAge;
};
CONST Pointers

const int * pCval;   // pointer to constant value
int * const pCpoint; // constant pointer to value
const int * const pCpointCval; // constant pointer to constant value
If you declare a pointer to a const object, the only functions that you can call with that pointer are const functions.
SimpleCat * pCat = new SimpleCat; // normal pointer to normal object
const SimpleCat * pConstCat = new SimpleCat; // pointer to constant object
SimpleCat  * const pConstpCat = new SimpleCat; //constant pointer to object

// GetWeight is a constant function == allowed in every case
cout << "pCat weight: " << pCat->GetWeigth() << " kg\n";
cout << "pConstCat weight: " << pConstCat->GetWeigth() << " kg\n";
cout << "pConstpCat weight: " << pConstpCat->GetWeigth() << " kg\n";

pCat->SetWeigth(20);
// pConstCat->SetWeigth(20); - not allowed, not a constant function
pConstpCat->SetWeigth(20);
// pConstpCat=pCat; - not allowed
References
target_variable_type & reference_name = target_variable_name;
Reference - is an alias - an another name for the same target object.
When you create a reference, you initialize the reference name with the name of another object, the target. From that moment on, the reference acts as an alternative name for the target. Anything will happen to the target object, it will happen also to the reference, and vice versa.
The compiler created really only a symbolic name with the same memory address as the target and no additional memory space. You can define the reference only once - as others variables.
unsigned short XVar;
unsigned short &rXVar = XVar; // reference to variable XVar

XVar=3;  // now XVar  == rXVar == 3
rXVar=7; // now rXVar == XVar  == 7
Passing Function Arguments by Reference
You can pass data to a function through 3 ways:
Passing by Value
The value in the argument is copied to the internal variable (located in the stack). Changing of the parameter inside of the function, doesn't have effect on the argument variable.
int XVar = 3;  // definition - global variable

void ChangeVar(int InVar) // definition - changing function
{
    InVar=99;
}

ChangeVar(XVar); // calling - variable XVar hasn't changed
			  // XVar=3
Passing by Address Using Pointers
The memory address of the argument is copied to the internal variable = pointer. Changing of the parameter changes directly the argument variable.
void ChangeVar(int * InVar) // definition - changing function
{
    *InVar=99;
}

ChangeVar(&XVar); // calling - variable XVar has changed
			   // XVar=99
Passing by Address Using Reference
The compiler uses the reference - the alias name of the original variable - which is in fact an address of the original variable.
void ChangeVar(int & InVar) // definition - changing function
{
    InVar=99;
}

ChangeVar(XVar); // calling - variable XVar has changed
			   // XVar=99
Passing by Reference for Efficiency
Each time you pass an object into a function by value, a copy of the object is made. Each time you return an object from a function by value, another copy is made.
Copy constructor - each of these temporary copies is created, the compiler calls a special constructor: the copy constructor.
class SimpleCat
{
public:
    SimpleCat();  // constructor
    SimpleCat(SimpleCat &);  // copy constructor
    ~SimpleCat(); // destructor 
...
};

SimpleCat CatVal(SimpleCat Cat) // CatVal - passes by value
{
    return Cat;
}

SimpleCat & CatRef(SimpleCat & rCat) // CatRef - passes by reference
{
    return rCat;
}

CatVal(Frisky);	// calling
	// copy global var Frisky to local var Cat (stack)
	// call copy constructor
	// RETURN - copy local var Cat to the stack
	// call copy constructor
	// call temporary return stack copy destructor
	// call local var Cat destructor (end of function)

CatRef(Frisky);	// calling
	// no copy, no copy destructor, no destructor
	// RETURN - no copy, no copy destructor, no destructor
You can see that passing by value is uneffective and time wasting, because the computer has to create copies of this object and to call the copy construcor and the destructor.
When you want to protect your object before changing, use the keyword const and after that you can use only const functions.
const SimpleCat & CatRef(const SimpleCat & rCat)
{
    rCat.GetWeight; // O.K.
    rCat.SetWeight(10); // not allowed
Pointer and References Pitfalls
►	To Declare More Pointers or References on the Same Line.
int * pVar1, pVar2;   // BAD - pVar2 is simply int variable, not pointer
int * pVar1, * pVar2; // O.K. - but bad readable code
int * pVar1;          // O.K. - perfect
int * pVar2;
►	To Declare Reference to the Null Object.
int * pInt = new int(5);

if (pInt != NULL)   // test for Null object
{	// rInt scope START
    int & rInt = *pInt;	// Warning: rInt has scope only inside braces
}	// rInt scope END
►	Returning a Reference to a Non-existent Object. 
SimpleCat & CatNon(void)
{
    SimpleCat George;	// local variable

    return George;	// return a reference to object won't exist
}	// local variable is destroyed
Advanced Functions
Overloading Constructors
Constructors, like all member functions, can be overloaded.
class Counter
{
public:
    Counter();  // constructor 1
    Counter(int initVal);  // constructor 2 - overloaded
    ~Counter(){}
    ...

// main 
Counter Counter1; //no argument - constructor 1 is called
Counter Counter2(2); //argument - constructor 2 is called
INITIALIZATION Stage of Constructors
The constructor definition has two stages: the initialization stage and the body. You can initialize the class data members either in the initialization stage, or in the body. It is cleaner, and often more efficient, to initialize member variables at the initialization stage.
class::constructor(parameters):variable(initval),variable(initval){body}

// constructor-parameters    - initialization list         - body
Cat::Cat(int age, int weight):catAge(age), catWeight(weight) {}
COPY Constructor
The copy constructor is called every time a copy of an object is made during another object creating. When you create an object and you use another object as init value, the copy constructor is called. When you pass an object by value as an argument of a function, or as a return value, a temporary copy of that object is made and the copy constructor is called.
The copy constructor has one parameter: a reference to an object of the same class.
class::constructor(class &) {}

SimpleCat(SimpleCat &);  // copy constructor

SimpleCat::SimpleCat(SimpleCat & myCat)  // user copy constructor
{}
The default copy constructor simply copies each member variable from the object passed as a parameter to the member variables of the new object. This is called a member-wise (or shallow) copy.
A shallow copy copies the member pointer variables 1:1. It can lead to a disaster, when the original is deleted, then the copy pointed to undefined memory space, this is stray pointer.
A deep copy copies the values allocated on the heap to newly allocated memory.

class Counter
{
public:
    ...
    Counter(const Counter &); // copy constructor - declaration
    int GetCountX() const { return *pcountX; }
private:
    int * pcountX;
}

// Copy Constructor - DEEP COPY - definition
Counter::Counter(const Counter & rhs)
{
    pcountX = new int(rhs.GetCountX()); // new pointer + copy data
}

// create object Counter2, init with Counter1 data
Counter Counter2(Counter1); // calls COPY CONSTRUCTOR
Counter Counter2 = Counter1; // calls COPY CONSTRUCTOR
NOTE: It is common to refer to the parameter to a copy constructor as rhs, which stands for right-hand side. 
OPERATOR Overloading
You can use operators (=, +, [], ...) directly with class by operator meaning overloading.
return_type operator operator_symbol (parameters) 
operator_symbol == overloaded operator.
class Counter
{
public:
    ...
    void operator++ () { ++countVal; } //operator "++" overloading - PREFIX
    ...

Counter Counter1(0); // object Counter1 definition with init

++Counter1; // calling - object increment - causes ++countVal
When you want to use an operator with a class in the assignment, you must have a return value in the operator overloading function.
    ...
    const Counter & operator++ (); // operator "++" overloading - PREFIX
    ...

const Counter & Counter::operator++ ()
{
    ++countVal;
    return *this; // *this == Counter1
}

Counter Counter1(0);

Counter Counter2 = ++Counter1; // ++Counter1, creates Counter2, copy
						// it calls copy constructor
Postfix Operator Overloading
You have to use the "int" type as the overloading parameter. The parameter's value is ignored; it is just a signal that this is the postfix operator.

    ...
    const Counter operator++ (int); // operator "++" overloading POSTFIX
    ...

const Counter Counter::operator++ (int)
{
    Counter CounterTemp(*this); // creates temporary object + copy data

    ++countVal;
    return CounterTemp; // returns countVal state before increment
}

Counter Counter1(0);

Counter Counter2 = Counter1++; // creates Counter2, copy, ++Counter1
+ (addition) Operator Overloading
Addition:
object_result = object1 + object2;
object1 "+" operator overloading function is called, object2 is the parameter of this function and temporary object is a result of this function.
    ...
    Counter operator+ (const Counter & rhs); //operator "+" overloading
    ...

Counter Counter::operator+ (const Counter & rhs)
{
    return Counter(countVal + rhs.GetVal() ); / temp. object
}

Counter C1(100), C2(11), Cres(0);

Cres = C1 + C2; // == 111
Operator Overloading Appendix
Overloaded operators can be member functions, as described in this chapter, or non-member functions. The only operators that must be class members are the assignment (=), subscript([]), function call (()), and indirection (->) operators.
Limitations on Operator Overloading:
•	built in types (int, char, ...) cannot be overloaded
•	the precedence order cannot be changed
•	you cannot make up new operators
•	you cannot redefine an operator meaning
•	overloaded operators cannot take default arguments
•	you cannot overload operators: #   .   .*   ::   ?:
•	the assignment operator (=) cannot be inherited
CONVERSION Operators
Conversion class_member <- int
You need to have defined a constructor with the parameter.
class Counter
{
public:
    Counter(int initVal):countVal(initVal){ };  // constructor with init
    ...

// main 
Counter count1 = 4; // call constructor with init value == 4
Conversion int <- class_member 
You need a special defined conversion operator function.
operator converted_type ()

class Counter
{
public:
    operator int(){ return countVal; }; // conversion operator
    ...

// main 
Counter CA(99); // call constructor with init value == 99
int IA = CA; // call conversion function int <- class_member
Arrays
Array element - one item of an array.
Fence post error - writing data paste the end of an array.
Heap - free memory store.
Array of Objects

class Cat
{
public:
    Cat():catAge(3) { }
    ~Cat();
    int GetAge() const { return(catAge); }
    void SetAge(int age) { catAge=age; } 
private:
    int catAge;
};

enum {MAXA=5};  // array dimension definition
Cat CatArray[MAXA]; // array of objects definition - constructor calling

CatArray[0].GetAge(); // class access
NOTE: The constructor is called MAXA times (in this case)!!!
Arrays and Pointers
Arrays and pointers definitions are very close. An array name is a constant pointer to the first element of the array
enum {MAX=5};
int arr[MAX] = {00,01,02,03,04};
int * parr = arr;

&arr[0]==arr==parr // the same address access
   arr[3]==3       // the same data access
  parr[3]==3
*(parr+3)==3
 *(arr+3)==3
A Pointer to an Array Versus an Array of Pointers

Cat   CatGroup[10]; // ARRAY of 10 cats (object)
Cat * CatGroup[10]; // ARRAY OF 10 POINTERS to cats
Cat * CatGroup = new Cat[10]; // POINTER TO ARRAY OF 10 cats
Array of Pointers to Object

enum {MAXC=5};
Cat * CatGroup[MAXC];//array of pointers to object - NO constructor calling
int xcat;

for (xcat=0;xcat<MAXC;++xcat)
{
    CatGroup[xcat]=new Cat;
    CatGroup[xcat]->SetAge(xcat+10); // access to object
}

for (xcat=0;xcat<MAXC;++xcat)
   delete CatGroup[xcat];     // delete
Pointer to Array of Objects

enum {MAXC=5};
Cat * CatPoint = new Cat[MAXC]; // pointer to array of objects
                                // 5 x CONSTRUCTOR calling
                                // NOT ALLOWED INIT constructor!
int xcat;

for (xcat=0;xcat<MAXC;++xcat)
    CatPoint[xcat].SetAge(xcat+20); // access to object

delete [] CatPoint; // [] == delete array, 5 x DESTRUCTOR calling
delete [] CatPoint - the brackets [] are the signal for the compiler that there is necessary to delete an array, not only a single object.
ATTENTION: The command delete CatPoint, deletes only 1 object *CatPoint==CatPoint[0]. 
delete [] CatPoint, deletes whole array.
NOTE: A constructor with the init part is by arrays not allowed!
STRING class
Definition Example

class String
{
public:
    // constructors
    String();                   // default constructor
    String(const String & rhs); // copy constructor - copy String object
    String(const char * const chstring);//constructor with char string init
    ~String();                  // destructor 

    // overloaded operators
    String & operator=(const String & rhs);
    String operator+(const String & rhs);

    // General accessors
    unsigned short GetLen()const { return strLen; }
    const char * GetString() const { return strString; }

private:
    String(unsigned short len); // private constructor
    char * strString;
    unsigned short strLen;
};
The private constructor serves only for internal using of the class functions.

String::String(unsigned short len)
{
    unsigned short xchar;

    strString = new char[len+1]; // string len=80, 80 chars+'\0'== 81 bytes 
    for (xchar=0; xchar<=len; ++xchar)
        strString[xchar] = '\0';   // zero filling 
    strLen=len;
}
The copy constructor serves for the objects copies.
// Copy constructor - copy String object
String::String (const String & rhs)
{
    unsigned short xchar;

    strLen=rhs.GetLen();
    strString = new char[strLen+1];
    for (xchar=0; xchar<strLen; ++xchar)
        strString[xchar] = rhs[xchar];
    strString[strLen] = '\0';
}
The constructor with a character array as a parameter is important for conversion.

// Constructor with init - converts a character array to a String 
String::String(const char * const chstring)
{
    unsigned short xchar;

    strLen = strlen(chstring);
    strString = new char[strLen+1];
    for (xchar=0; xchar<strLen; ++xchar)
        strString[xchar] = chstring[xchar];
    strString[strLen]='\0';
}

// Destructor - frees allocated memory
String::~String ()
{
    delete [] strString; // array delete
    strLen = 0;
}

// = Equal operator overloading
String & String::operator=(const String & rhs)
{
    unsigned short xchar;

    if (this == &rhs)
        return *this;
    delete [] strString;
    strLen=rhs.GetLen();
    strString = new char[strLen+1];
    for (xchar=0; xchar<strLen;++xchar)
        strString[xchar] = rhs[xchar]; // copy string
    strString[strLen] = '\0';
    return *this;
}

// + Concatenation - creates a new string by adding current
String String::operator+(const String & rhs)
{
    unsigned short totalLen = strLen + rhs.GetLen();
    String temp(totalLen);
    unsigned short xchar,ychar;

    for (xchar=0; xchar<strLen; ++xchar)
        temp[xchar] = strString[xchar];
    for (ychar=0; ychar<rhs.GetLen(); ++ychar, ++xchar)
        temp[xchar] = rhs[ychar];
    temp[totalLen]='\0';
    return temp; // call copy constructor
                 // call destructor for temp
}
Using Examples - Equation

String s1; // default constructor
char str1[]= "2222222222";

s2 = str1; // copy constant string to object
Program will do:
1 -	calls Constructor with init - String(const char *const chstring)
program creates "inner_temp" - Internal Temporary String object as an output for this constructor
2 -	calls Equal operator overloading - String & String::operator=(const String & rhs)
rhs == inner_temp (Internal Temporary String object)
this == s2 == left side of the equation
in this case is the function return not necessary, it is prepared for statements: a = b = c
3 -	calls Destructor for "inner_temp" - Internal Temporary String object
The automatic creation of the temporary object is known as implicit casting, or promotion. If you had not declared this conversion constructor, this assignment would have generated a compiler error. 
Using Examples - Concatenation

String s1("1111"), s2("2222"), s3;

s3 = s1+s2; // concatenate == join two strings
Program will do:
1 -	calls Concatenation - String String::operator+(const String & rhs)
rhs == s2 == right from '+' sign
this == s1 == left from '+' sign
statement "return temp;" will do
	call copy constructor - copy local temp variable to stack to "inner_temp" variable
		("inner_temp" - Internal Temporary String object) 
	call destructor for "temp"
return value == "inner_temp" - Stack copy of temp
2 -	calls Equal operator overloading - String & String::operator=(const String & rhs)
rhs == inner_temp - Internal Temporary String object
this == s3 == left side of the equation
in this case is function return not necessary, it is prepared for statements: a = b = c
3 -	calls Destructor for "inner_temp" - Internal Temporary String object - Stack copy of "temp"
DERIVATION (INHERITANCE)
A class which adds a new functionality to an existing class is said to derive from that original class. The original class is said to be the new class's base class. The derived class inherits the functionality of the base class. This is also called a relationship.
class Derived : public Base_class
NOTE: The derived class inherits all data members and functions from the base class except constructors and the destructor!
The base class is usually more general and more universal, the derived class is more specific and particular.
enum BREED { YORKIE, CAIRN, DANDIE, SHETLAND, DOBERMAN };

class Mammal
{
public:
    Mammal():itsAge(2), itsWeight(5){} // constructors
    ~Mammal(){}

    int GetAge()const { return itsAge; } //accessors
    void SetAge(int age) { itsAge = age; }
    int GetWeight() const { return itsWeight; }
    void SetWeight(int weight) { itsWeight = weight; }

    //Other functions
    void Speak()const { cout << "Mammal sound!\n"; }
    void Sleep()const { cout << "shhh. I'm sleeping.\n"; }

protected:
    int itsAge;
    int itsWeight;
};

class Dog : public Mammal // class Dog derived from Mammal
{
public:
    Dog():itsBreed(YORKIE){} // Constructors
    ~Dog(){}

    BREED GetBreed() const { return itsBreed; }  // Accessors
    void SetBreed(BREED breed) { itsBreed = breed; }

    // Other functions
    void WagTail() { cout << "Tail wagging...\n"; }
    void BegForFood() { cout << "Begging for food...\n"; }
    
private:
    BREED itsBreed;
};
protected - protected members are fully visible to derived classes, but are otherwise private. private members are not available to derived classes.
Dog fido; // calls mammal constructor
          // calls dog constructor

fido.Speak(); // inherited function from Mammal class
fido.WagTail(); // new function from Dog class

} // calls dog destructor
  // calls mammal destructor
Dog objects are Mammal objects. 
When Dog fido is created, the Mammal constructor is called at first, then the Dog constructor is called.
When fido is destroyed, first the Dog destructor will be called and then the destructor for the Mammal part of fido.
// Dog - base constructor
Dog::Dog():
Mammal(),  // explicit call, otherwise it will be called by default
itsBreed(YORKIE)
{}

// Dog - init constructor
Dog::Dog(int age, int weight, BREED breed):
Mammal(age),    // init Mammal.istAge = age
itsBreed(breed) // init Dog.itsBreed = breed
{
    itsWeight=weight; // you can't do it in the initialization phase
}
NOTE: You cannot assign to the base class variable in the initialization phase. When you don't have a proper base class constructor, you must to do it within a derived class constructor.
OVERRIDING Functions
Overriding - a derived class creates a function with the same return type and signature as a member function in the base class, but with a new implementation -- the same head, the different body.
Signature - the signature of a function is its name, and the number and type of its parameters.
class Mammal
{
...
    void Speak()const { cout << "MAMMAL - speak. AAGGRRHH\n"; }
    void Speak(long times)const { cout << "Speak " << times << " x\n"; }
...

class Dog : public Mammal
{
...
    void Speak()const { cout << "DOG - speak - WOOOOF. (Overrided)\n"; }
...
ATTENTION: When you override a base class function, you will lose the access to all overloaded functions (it hides the functions)! You must to override all functions which do you want to have access to.
You can call the overridden base function by fully qualifying calling the name of the function - explicit calling:
object_name.base_class_name::function_name();
Calling:
Mammal beast;
Dog fido;

beast.Speak();   // calls Mammal.Speak()
beast.Speak(2);  // calls Mammal.Speak(long times)
fido.Speak();    // calls Dog.Speak()
// fido.Speak(2); // attempt to call Mammal.Speak(long times) - error
fido.Mammal::Speak(999); // calls Mammal.Speak(long times)
VIRTUAL Functions
Virtual function (method) - is a function that you expect to be redefined in derived classes. When you refer to a derived class object using a pointer or a reference to the base class, you can call a virtual function for that object and execute the derived class's version of the function.
virtual void Function1(); // Base_class - virtual function definition
...
void Function1(); // Derived_class - function overriding
...
Base_class * pBase_class = new Derived_class; // pointer definition
pBase_class->Function1(); // calls Derived_class.Function1()
Example:
class Mammal
{
...

    virtual void Speak()const { cout << "MAMMAL - speak. AAGGRRHH\n"; }
    void Move()const { cout << "MAMMAL - move.\n"; }
...

class Dog : public Mammal
{
...
    void Speak()const { cout << "DOG - speak - WOOOOF. (Overrided)\n"; }
...

class Cat : public Mammal
{
...
    void Speak() const { cout << "CAT - speak - MEOWWWW. (Overrided)\n"; }

// using
Mammal * pMammal1 = new Dog; // relationship - you can do this
Mammal * pMammal2 = new Cat; 
// Dog * pDog = new Cat; // no relationship - you mustn't do this

pMammal1->Move(); // Move is not virtual - calls Mammal.Move()
pMammal1->Speak();  // Speak is virtual - calls Dog.Speak()
pMammal2->Speak();  // Speak is virtual - calls Cat.Speak()
Dynamic binding, or Run-time binding - a pointer is bound with an object and functions at runtime, not at compile time. 
Example:
Mammal * pMammal1;

if (xy>1)
    pMammal1 = new Dog; // run-time binding
Derived Object Creating

Dog fido; // 1 - calls mammal CONSTRUCTOR - BASE CLASS
          // 2 - calls dog CONSTRUCTOR - DERIVED CLASS
...
} // out of scope
  // 1 - calls dog DESTRUCTOR - DERIVED CLASS
  // 2 - calls mammal DESTRUCTOR - BASE CLASS
The Dog object in memory:

Dog fido

Mammal
	
Dog
	
Virtual Function Table (v-table), Virtual Table Pointer (v-pointer)
Virtual Function Table (v-table) - a table of references to virtual functions. One v-table is per class.
Virtual Table Pointer (v-pointer, vptr) - pointer to v-table. One v-pointer is per object.
When the Mammal part of the object is created, the virtual pointer points to Mammal.Speak(). After that, when the Dog part of the object is created, the virtual pointer is adjusted to Dog.Speak().
NOTE: Virtual functions operates only on pointers and references. Passing an object by value will not enable the virtual functions to be invoked.
Virtual Destructor
ATTENTION: If any of the functions in your class are virtual, the destructor should be as well!
When the destructor of the Mammal class isn't virtual, then by deleting Dog fido object will be called only Mammal destructor. When the Mammal destructor is virtual, the Dog destructor is called as first and after that the Mammal destructor.
Virtual Copy Constructor
NOTE: Virtual constructors are forbidden!
Therefore when you need to create a virtual copy constructor you need to create the Clone() function, to override it and to make it virtual.
Example:
class Mammal
{
...
    Mammal(const Mammal & rhs):itsAge(rhs.GetAge()) { } // copy constructor
    virtual Mammal * Clone() { return new Mammal(*this); } // clone
...

class Dog : public Mammal
{
...
    Dog(const Dog & rhs):Mammal(rhs){ } // copy constructor
    virtual Mammal * Clone() { return new Dog(*this); } // clone
...

// using
    Mammal * pMammal1 = new Dog; 
    Mammal * pMammal2; 

    pMammal2=pMammal1->Clone();
        // Program will do:
        // 1 - calls Dog.Clone()
        //    2 - Dog.Clone() calls Dog.Dog(*this) - copy Dog
        //       3 - Dog.Dog(*this) calls Mammal.Mammal(rhs) - copy Mammal
        //       4 - calls body of Mammal.Mammal(rhs)
        //    5 - return to Dog.Dog(*this)
        //    6 - calls body of Dog.Dog(*this)
        // 7 - return to Dog.Clone()
        // 8 - calls body of Dog.Clone()
Percolating upward - when you have two derived classes with the same function (Horse.Eat(), Bird.Eat()), you can move this function up to the base class and to create the virtual function (Animal.Eat()).
Special Classes and Functions
Abstract Data Types
Abstract Data Type (ADT) - represents a concept (like Shape class) rather than an object (like Circle). In C++, an ADT is always the base class to other classes, and it is not valid to make an instance of an ADT. 
The Shape class exists only to provide an interface for the classes derived from it (Shape // Rectangle // Square).
class Shape
{
public:
    Shape(){}
    virtual void Draw() {}
...

class Rectangle : public Shape
{
public:
    Rectangle(int len, int width):itsLength(len), itsWidth(width){}
    virtual void Draw();
private:
    int itsWidth;
    int itsLength;
};

class Square : public Rectangle
{
public:
    Square(int len):Rectangle(len,len){}
...

// Using:
Shape * pShape;

pShape = new Rectangle(4,6);
pShape->Draw(); // calls Rectangle::Draw()

pShape = new Square(8);  // init Rectangle(8,8)
pShape->Draw(); // calls Rectangle::Draw()
Pure Virtual Functions
Pure Virtual Function - is made pure by initializing it with zero:
virtual void Draw() = 0;
ATTENTION: Any class with one or more pure virtual functions is an ADT, and it is illegal to instantiate the object of the class.
ATTENTION: You must to override all pure virtual functions from the base class or you will create an ADT again!
It is possible, however, to provide an implementation to a pure virtual function -- you can call it by explicit call.
class Shape // ADT == Abstract Data Type
{
public:
    virtual void Draw() = 0; // Pure Virtual Function
...

void Shape::Draw()
{
    cout << "Shape - abstract drawing part\n";
}
STATIC Member Data
NOTE: Static member variables are shared among all instances of a class. Static members are one per class. They belong to the class, not to the object.
class Cat
{
public:
    ...
    static int HowManyCats; // static member data - no memory allocation
                            // only declaration
    ...

int Cat::HowManyCats = 0; // definition - memory allocation 

// Using:
i=Cat::HowManyCats; // call - class::static_data
NOTE: The declaration of HowManyCats into Cat class, doesn't allocate memory. You have to define it extra, outside of the class.
Accessing Static Members Using Non-static Member Functions. 
class Cat
{
public:
    ...
    virtual int GetHowMany() { return HowManyCats; }
private:
    static int HowManyCats;
    ...

int Cat::HowManyCats = 0;

// Using:
Cat * pCat = new Cat;

i=pCat->GetHowMany(); // call - non-static member function
Static Member Functions
Static member functions are connected with a class, not with a object.
class Cat
{
public:
    ...
    static int GetHowMany() { return HowManyCats; }
private:
    static int HowManyCats;
    ...

int Cat::HowManyCats = 0;

// Using:
i=Cat::GetHowMany(); // call - static member function - without object
NOTE: Static member functions do not have a this pointer. Therefore, they cannot be declared const. Also, because member data variables are accessed in member functions using the this pointer, static member functions cannot access any non-static member variables!
Pointers to Member Functions
pFunc points to a member function of the class Shape, which takes two integers and returns void.
void (Shape::*pFunc) (int, int); 
Example:
void (Mammal::*pFunc)() const = NULL;
Mammal * pMammal =0; 

pMammal = new Cat;

pFunc=Mammal::Speak;

(pMammal->*pFunc)();
Example with array of pointers to function:
typedef void (Dog::*PDF)()const ; 
const int MaxFuncs = 2;
PDF DogFunctions[MaxFuncs] = { Dog::Speak, Dog::Move };

Dog * pDog = new Dog;

(pDog->*DogFunctions[1])(); 
Advanced Inheritance
Multiple Inheritance (Derivation)
Multiple Inheritance - deriving a new class from more than one base class.
class Derived : public Base_class1, public Base_class2
Object creating:
class Pegasus : public Horse, public Bird

// Using:
Pegasus * pPeg = new Pegasus;
   // 1 - calls Horse CONSTRUCTOR - BASE CLASS
   // 2 - calls Bird CONSTRUCTOR - BASE CLASS
   // 3 - calls Pegasus CONSTRUCTOR - DERIVED CLASS
...
delete pPeg
   // 1 - calls Pegasus DESTRUCTOR - DERIVED CLASS
   // 2 - calls Bird DESTRUCTOR - BASE CLASS
   // 3 - calls Horse DESTRUCTOR - BASE CLASS
The Pegasus object in memory:

Horse

Pegasus

Bird
	
Pegasus
	
Ambiguity
When your base classes (Horse, Bird) have the same function name (GetColor()), then you can't call this function directly, because the compiler will be confused (it leads to compiler error). You have to use an explicit call, or the function overriding with an explicit call inside.
Pegasus * pPeg = new Pegasus;
// Without overriding:
// pPeg->GetColor(); // ERROR - ambiguity
pPeg->Horse::GetColor(); // O.K. - explicit call

// Overriding:
class Pegasus : public Horse, public Bird
{
public:
    COLOR GetColor() const { return Horse::GetColor(); }
...
// using
pPeg->GetColor(); // O.K. - overriding
Shared Base Class
When your classes Horse and Bird inherit from the base class Animal, there is an another ambiguity.
class Animal // common base to both horse and bird
{
public:
    virtual int GetAge() const { return itsAge; }
...

class Horse : public Animal
...

class Bird : public Animal
...

class Pegasus : public Horse, public Bird
{
public:
    int GetAge() const { return Horse::GetAge(); } 
...

// Using:
Pegasus * pPeg = new Pegasus;
  // Constructor calls: Animal, Horse, Animal, Bird, Pegasus
...
delete pPeg
  // Destructors call: Pegasus, Bird, Animal, Horse, Animal
Simply call GetAge() is an ambiguity because Pegasus has inherited two functions Horse::GetAge() and Bird::GetAge().

Animal

Animal

Memory:	Inheritance:
Animal

Bird

Horse

Horse

Pegasus

Animal

Pegasus

Bird
	
Pegasus
	
Virtual Inheritance
When you make the base class Animal virtual for Horse and Bird, then you have only one copy of Animal class and you can call the function GetAge() directly.
class Animal 
{
public:
    virtual int GetAge() const { return itsAge; }
...

class Horse : virtual public Animal
...

class Bird : virtual public Animal
...

class Pegasus : public Horse, public Bird
...

// Using:
Pegasus * pPeg = new Pegasus;
  // Constructor calls: Animal, Horse, Bird, Pegasus
...
delete pPeg
  // Destructors call: Pegasus, Bird, Horse, Animal

Animal

Pegasus

Memory:	Inheritance:
Animal

Pegasus

Bird

Horse

Horse
	
Bird
	
Pegasus

NOTE: DON'T use multiple inheritance when single inheritance will do. It can be too complex and too complicated.
Mixin , or capability class - is a class that adds functionality without adding much or any data. 
Containment, Delegation
Containment - the outer class contains the inner class. Thus, an Employee class might contain string objects.
Delegation - using the attributes of a contained class to accomplish functions not otherwise available to the mother class.
class String
{
public:
    ...
    const char * GetString() const { return itsString; }
private:
    char * itsString;
    ...

class Employee
{
public:
    ...
    const String & GetFirstName() const { return itsFirstName; }
    void SetFirstName(const String & fName) { itsFirstName = fName; }
private:
    String    itsFirstName; // class in class
    ...

// Using:
Employee Edie("Jane");
string1=Edie.GetFirstName().GetString(); // access
Edie.SetFirstName("Edythe");
// Program will do:
// 1 - calls SetFirstName
// 2 - calls string convertor - String::String(const char * const cString)
//       creates temporary String
// 3 - calls = operator overloading - String & String::operator=(const String & rhs)
// 4 - returns to SetFirstName
// 5 - calls destructor temporary String

// Edie.itsFirstName.itsString="xx"; // NO ACCESS to String member data
Private Derivation
Private Derivation - you inherit all functionality of a base class, but the next inheritance won't have access to this base class.
class C1
{
public:
    void C1public() { cout << "Class C1 PUBLIC part\n"; }
private:
    void C1private() { cout << "Class C1 PRIVATE part\n"; }
};

class C2 : private C1
{
public:
    void C2public() { cout << "Class C2 PUBLIC part -- "; C1public(); 
                      /* C1private(); // NO ACCESS */ }

private:
    void C2private() { cout << "Class C2 PRIVATE part\n"; }
};

class C3 : public C2
{
public:
    void C3public() { cout << "Class C3 PUBLIC part\n"; }
private:
    void C3private() { cout << "Class C3 PRIVATE part\n"; }
};

// Using:
C1 xc1;
C2 xc2; // class C2 : private C1
C3 xc3; // class C3 : public C2

// xc1.C1private(); // no access
xc1.C1public(); // O.K.

// xc2.C1public(); // NO ACCESS - private inheritance
xc2.C2public(); // O.K. - internal call C1public

// xc3.C1public(); // NO ACCESS - private inheritance
xc3.C2public(); // O.K. - public inheritance
xc3.C3public(); // O.K.
FRIEND Classes
Friend Classes - if you want to expose your private member data or functions to another class, you must declare that class to be a friend. 
Friendship cannot be transferred -- friendship defining is only for two classes (no next inheritance).
Friendship is not valid in reverse -- when a class A is a friend of a class B, then the class B is not automatically a friend of the class A.
class C10
{
public:
    friend class C20;
private:
    int itsC10;
    void C10private() { cout << "Class C10 PRIVATE part --"; }
};

class C20
{
public:
    void C20public() { cout << "Class C20 PUBLIC part. -- "; 
        C10 xC10; xC10.C10private(); 
        cout << "C10 data - its10=" << xC10.itsC10 << endl; }
    ...

// Using:
C10 xc10; // friend class C20
C20 xc20; 

// xc10.C10private(); // no access
// xc20.C10public(); // NO ACCESS - no inheritance
xc20.C20public(); // O.K.
Friend Functions
Friend functions - you can also declare only one function as a friend -- it can be a class member function, or any other function.

class C20
{
public:
    void C21public();
    ...

class C11
{
public:
    C11() { itsC11=11; }
    friend void C20::C21public();
private:
    int itsC11;
    void C11private() { cout << "Class C11 PRIVATE part --"; }
};

void C20::C21public()
{
    C11 xC11;
    xC11.C11private(); // access to private data
    cout << "C11 data - its11=" << xC11.itsC11 << endl; 
}
Streams
Basic IO classes (iostream.h):
•	ios - is the base class to the input and output stream classes. The ios class has a streambuf object as a member variable. 
•	streambuf - class manages the buffer -- fill, empty, flush, ...
•	istream and ostream - classes derive from the ios class and specialize input and output stream behaviour, respectively. 
•	iostream - class is derived from both the istream and the ostream classes and provides input and output functions for writing to the screen. 
•	fstream - classes provide input and output from files.
When a C++ program that includes the iostream classes starts, four objects are created and initialized:
•	cin (pronounced "see-in")  - handles input from the standard input, the keyboard. 
class: istream	header file: iostream.h	default object: istream cin;
•	cout (pronounced "see-out") - handles output to the standard output, the screen. 
class: ostream	header file: iostream.h	default object: ostream cout;
•	cerr (pronounced "see-err") - handles unbuffered output to the standard error device, the screen. Because this is unbuffered, everything sent to cerr is written to the standard error device immediately, without waiting for the buffer to fill or for a flush command to be received. 
•	clog (pronounced "see-log") - handles buffered error messages that are output to the standard error device, the screen. It is common for this to be "redirected" to a log file.
Redirecting - refers to sending output (or input) to a place different than the default. The redirection operators for DOS and UNIX are '<' redirect input and '>' redirect output.
Piping - refers to using the output of one program as the input of another.
cin using:
int someVariable; 
cin >> someVariable; // keyboard input written to the someVariable
// cin has overloaded the extraction operator ">>" 
// for all types of parameters: int&, short&, long&, double&, ...
// for int is called:
istream & operator >> (int &) 
// cin is a istream object
// return value of cin is a reference to an istream object
// you can write:
cin >> VarOne >> varTwo >> varThree; 
IOSTREAM Class Hierarchy Diagram

ios
├─ istream ──────┐
│  └─ ifstream   │
│                ├─ iostream
│                │  └─ fstream
└─ ostream ──────┘
   └─ ofstream

streambuf          (called by iostream)
└─ filebuf

class: ios, istream,  ostream	header file: iostream.h
class:      ifstream, ofstream	header file: fstream.h
TEXT - Formatting (IOS)

Function	Description	
setf()	Turns ON specified flags (format bits). It returns the previous value of all the flags. To combine these flags use bitwise OR '|' operator.
long setf( long lFlags );	
unsetf()	Turns OFF specified flags (format bits). It returns the previous value of all the flags. To combine these flags use bitwise OR '|' operator.
long unsetf( long lFlags );	
flags()	Sets the stream’s internal flags variable to lFlags and returns the previous value. ALL FLAGS TOGETHER!
long flags( long lFlags );	
setw()	Sets the minimum field width. Changes only next output field! If the number of characters is greater, all characters are printed (no truncated).
SMANIP( int ) setw( int nw );	

lFlags - format flags value for the stream (bitwise values). 

Flag	Description	
left	Left justification.	
right	Right justification (default).	
dec	Decimal format of values (default).	
hex	Hexadecimal format of values.	
showpoint	Shows decimal point and trailing zeros for floating-point values.	
uppercase	Displays uppercase A through F for hexadecimal values and E for scientific values.	
Examples:
long mflags;

/* example ................................ output */
mflags=cout.setf(ios::left | ios::hex); // sets flags forever
cout << setw(10) << 255;  /* Out :  |ff        | */
cout.flags(mflags); // returns back original value
ATTENTION: Change of a flag changes stream behaviour till the end of the program!
TEXT - INPUT (ISTREAM)

Function	Description	
get()	Extracts data from input stream. Saves chars to pch[nCount], nCount == max chars included '\0', delim == delimiter char ('\n' - default). The delimiter is read and stays in the buffer!
istream & get(char * pch, int nCount, char delim = '\n');
istream & get(); // returns 1 char	
getline()	Extracts data from input stream. Saves chars to pch[nCount], nCount == max chars included '\0', delim == delimiter char ('\n' - default). The delimiter is read and thrown away.
istream & getline(char * pch, int nCount, char delim = '\n');	
ignore()	Extracts and discards up to nCount characters. delim == delimiter char ('\n' - default). The delimiter is read and thrown away.
istream & ignore(int nCount, char delim = '\n');	
>>	Extraction operator.
istream& operator >>( char* psz );
istream& operator >>( int& n );
...	
Examples:
char ch, cha1[255];

cin.get(ch); // read 1 char
cin.get(cha1,255); // default delimiter '\n' 
                   // '\n' stayed in buffer
cin.ignore(255,'\n');  // discards '\n'
cin.getline(cha1,255); // read 1 line of chars, discards '\n'
cin >> cha1;  // read 1 line
TEXT - OUTPUT (OSTREAM)

Function	Description	
put()	Inserts a single character into the output stream.
ostream & put(char ch);	
<<	Insertion operator.
ostream& operator <<( char ch );
ostream& operator <<( int n );
...	

Manipulator	Description	
endl	Inserts a newline character and then flushes the buffer.	
ends	Inserts a null-terminator character.	
Examples:
cout.put(ch); // write 1 char to display
cout << "string" << 255 << endl; // write string + integer + '\n'
FILE - Base (FSTREAM)
fstream.h
•	ifstream - input file stream - class for reading data from a file.
•	ofstream - output file stream - class for reading and writing data from / to a file.
For a file access you must create an ofstream object -- derived from iostream object.

FILE - Status Tests (IOS)

Function	Description	
eof()	eof() == TRUE  (!=0) if end of file has been reached.
int eof()	
bad()	bad() == TRUE  (!=0)  you attempt an invalid operation.
int bad()	
fail()	fail() == TRUE  (!=0) any I/O error has occurred. If a bad()==0 you can probably continue processing after you clear the flags.
int fail()	
good()	good() == TRUE  (!=0) if all error bits are clear (not eof() && not bad() && not fail()).
int good()	
rdstate()	Returns the current error state as specified by the following masks (ios enumerators). To combine these masks use bitwise AND '&' operator.
ios::goodbit - No error condition.
ios::eofbit - End of file reached.
ios::failbit - A possibly recoverable formatting or conversion error.
ios::badbit - A severe I/O error or unknown state. 
int rdstate() const;	
clear()	Sets or clears the error-state flags. If 0, all error bits are cleared; otherwise bits are set according to the following masks (ios enumerators) that can be combined using the bitwise OR '|' operator.
void clear( int nState = 0 );	
FILE - Basic Manipulating (FSTREAM)

Function	Description	
open()	Opens a disk file. Name = file name, Mode = opening mode, Prot = type of protection.
fstream(char * Name, int Mode, int Prot = filebuf::openprot );	
close()	Flushes any waiting output and closes the file	
flush()	Empties output buffer.
ostream & flush();	
Examples:
fstream myfile("xfile.txt",ios::app,filebuf::openprot);
FILE - Open Modes (IOS)

Mode	Description	
app	Appends data after the end of existing file.	
in	Opens file for input.	
out	Opens file for output. If the file already exists, its contents are discarded.	
trunc	If the file already exists, its contents are discarded (default mode).	
nocreate	If the file does not exist, the open fails.	
noreplace	If the file does already exist, the open fails.	
binary	Opens file in the binary mode (text mode is default)	
NOTE: ios enumerators  can be combined with the bitwise OR '|' operator. 
FILE - Protection Type (FILEBUF)

Mode	Description	
openprot	Default.	
sh_compat	Compatibility share mode (MS-DOS only).	
sh_none	Exclusive mode — no sharing.	
sh_read	Read sharing allowed.	
sh_write	Write sharing allowed.	
NOTE: The filebuf::sh_read and filebuf::sh_write modes can be combined with the logical OR '||' operator.
Standard file manipulating:
ofstream myfile(fileName);  // create object myfile == OPEN file
myfile << "text\n";         // insert operator == WRITE data to file
myfile.close();             // CLOSE the file - flush the data
Examples:
char fileName[80]="filetest.txt"; // possible path: C:\\dir\\filename
char inch;  

//--- Creating new file - writing ------------------------------
ofstream myfout(fileName);  // OPEN - OUTPUT/INPUT file stream myfout
                // if the file already exists, its contents are thrown away
ofstream myfout2(fileName,ios::app);  // OPEN for append

if (!myfout) // FILE OPEN VALIDITY TEST!
             //  if(myfout)  ==  if (myfout.good())
             //  if(!myfout) ==  if (myfout.fail())
{
    cout << "Unable to open " << fileName << " for appending.\n";
    return;
}

myfout << "Write 1 line...\n"; // WRITE to file
myfout.close();  // CLOSE the file - flush the data

//--- Opening existing file - reading --------------------------
ifstream myfin(fileName);  // OPEN - INPUT file stream myfin
while (myfin.get(inch)) // while input character != EOF read 1 char
    cout << inch;
myfin.close();   // CLOSE the file - flush the data
ATTENTION: Test each file opening to ensure that it is opened successfully! Reuse existing streams objects. Close all fstream objects when you are done using them!
FILE - BINARY - INPUT/OUTPUT (ISTREAM/OSTREAM)

Function	Description	
read()	Reads nCount bytes from a stream to *pch.
istream & read(char * pch, int nCount)	
gcount()	Counts the characters extracted in the last unformatted operation.
int gcount();	
write()	Writes nCount bytes from *pch to a stream.
ostream & write(char * pch, int nCount)	
Binary file manipulating:
ofstream myfout(bfileName,ios::binary); // create binary file
myfout.write((char *) & Bear1,sizeof Bear1); // write binary data
// typecasting (char *) & Bear == use address of Bear as a char pointer
myfout.close();
Examples:
class Animal
    {
    public:
        Animal(int weight, long days):
            itsWeight(weight),itsNumberDaysAlive(days){}
        ~Animal(){}
        ...
    private:
        int itsWeight;
        long itsNumberDaysAlive;
    };

Animal Bear1(15,255);

ofstream myfout(fileName,ios::binary);
if (!myfout)                 
{
    cout << "Unable to open " << fileName << " for writing.\n";
    return;
}
myfout.write( (char *) & Bear1,sizeof Bear1);
myfout.close();
NOTE: Only the data from a class are saved to the disk -- no functions.
FILE - BINARY - File Pointer Moving (ISTREAM/OSTREAM)
OSTREAM

Function	Description	
seekp()	Changes the file’s put pointer. 
pos = position from the start of the file (0 = the first byte)
off = new offset value
dir = seek direction:
	ios::beg - Seek from the beginning of the file.
	ios::cur - Seek from the current position in the file.
	ios::end - Seek from the end of the file. 
ostream& seekp( streampos pos );
ostream& seekp( streamoff off, ios::seek_dir dir );	
tellp()	Reads the value of the file’s put pointer.
streampos tellp();	
ISTREAM

seekg()	Changes the file’s get pointer.
istream& seekg( streampos pos );
istream& seekg( streamoff off, ios::seek_dir dir );	
tellg()	Reads the value of the file’s get pointer.
streampos tellg();	
Exceptions Handling
TRY, CATCH, THROW
Exception - is a predictable problem such as running out of resources (memory or disk space). In C++ is an exception also an object that is passed from the area of code where a problem occurs to the part of the code that is going to handle the problem.
Try block - is a block surrounded by braces in which an exception may be shown.
Catch block - is the block immediately following a try block, in which exceptions are handled.
Throw - return from a function with an exception test, jump to catch block.
class Array
{
    Array(int itsSize = DefaultSize);
    ...
    // Exception class definition:
    // - serves only for exception connection to CATCH !!!
    class xZero {};      // exception for x == 0
    // hidden default functions: default constructor, destructor, copy
    // constructor, copy operator (=) 
    class xNegative {};  // exception for x < 0
    ...

// Exception tests:
Array::Array(int size = DefaultSize): 
itsSize(size)
{
    if (size==0) //size is out of range == jump to catch(Array::xZero)
        throw xZero(); 
    if (size<0)
        throw xNegative(); // size is out of range == jump to catch(...)

// Exception handling:

// without handling - program crashes - Debug Error
try // a part of program with exception possibility
{
    Array IntArray(0);
}
catch(Array::xZero) // exception handler - called from throw xZero();
{
    cout << "Error - index is == 0 \n";
}
catch(...) // catch anything else - called from throw xNegative();
{
    cout << "Error - index is < 0 \n";
}
Data Transfer

class Array
{
    Array(int itsSize = DefaultSize);
    ...
    // Exception class definition:
    class xSize
    {
    public:
        xSize(int size):itsSize(size) {}
        ~xSize(){}
        virtual int GetSize() { return itsSize; }

        virtual void PrintError()
            {cout << "Size error. Size: " << itsSize << endl; }
    protected:
        int itsSize;
    };

    class xTooBig : public xSize // inheritance
    {
    public:
        xTooBig(int size):xSize(size){}
        virtual void PrintError() 
            {cout << "Too big. Size: " << xSize::itsSize << endl; }
    };

    class xTooSmall : public xSize
    {
    public:
        xTooSmall(int size):xSize(size){}
        virtual void PrintError() 
            {cout << "Too small. Size: " << xSize::itsSize << endl; }
    };
    ...

// Exception tests:
Array::Array(int size = DefaultSize): 
itsSize(size)
{
// size is out of range == jump to catch(Array::xSize & theException)
    if (size<2)
        throw xTooSmall(size); 
// size is out of range == jump to catch(Array::xSize & theException)
    if (size>100)
        throw xTooBig(size); 

// Exception handling:
try 
{
    Array IntArray(1);
}

//--- Exception with data ----
// xSize theException - calls xSize.PrintError
// xSize & theException - calls xTooSmall.PrintError ... and others
// Virtual functions works only with pointers and references !!!
catch(Array::xSize & theException)
{
    theException.PrintError();
}
ATTENTION: An exception means, something has gone wrong. Therefore you have to avoid accumulating this problem. For example when you are out of memory, don't try to allocate memory in exception classes.
Specialities
Templates - Basic

template < [typelist] [, [ arglist ]] > declaration
Template - a set of parametrized classes or functions.
typelist - list of types in the form: class identifier, or typename identifier
template <class T> // template declaration 
class Array
{
public:
    Array(int itsSize);
    ~Array() { delete [] pType; }

    T & operator[](int offSet) { return pType[offSet]; }
    const T & operator[](int offSet) const { return pType[offSet]; }
private:
    T * pType; // pType[itsSize] == array of itsSize x T object
    int itsSize;
};

// outside of class is reference: Array<T>
template <class T> // template - class function definition
Array<T>::Array(int size = DefaultSize): 
itsSize(size)
{
    pType = new T[size]; // pType[itsSize] == array of itsSize x T object
    ...

Array<int> IntArray(10); // template - object creating - integer array
Array<Animal> AnimalArray(10); // class Animal

IntArray[1] = 10;
AnimalArray[1].SetWeight(20);
Templates - Function

void SomeFunction(Array<int>&);    // ok
void SomeFunction(Array<T>&);   // error! - no idea about size of T
void SomeFunction(Array &);     // error! - Array is a template no class
To accomplish the more general approach, you must declare a template function.
template <class T>
void MyTemplateFunction(Array<T> & MyArray);    // ok
Non-template Friend Function

friend void Intrude(Array<int> myArray); // not a template - only int array
Template Friend Function

template <class T>
class Array
{
    ...
 friend ostream & operator<<(ostream & output, const Array<T> & theArray);
    ...

template <class T>
ostream & operator<< (ostream & output, const Array<T> & theArray)
{
    for (int i = 0; i<theArray.GetSize(); i++)
        output << "[" << i << "] " << theArray[i] << endl;
    return output;
}

// Using:
Array<int> IntArray; // template - object creating

cout << IntArray << endl;
ASSERT - Macro for Debugging

//--- DEBUG definitions ---
#define DEBUG

// if it's not DEBUG mode DO nothing
// if it is DEBUG mode check error
// '\' == continuation on the next line
// if x==FALSE the print error message
// #x == print string "x", x == macro input expression
#ifndef DEBUG
	#define ASSERT(x)
#else

	#define ASSERT(x) \
			if (! (x)) \
			{ \
				cout << "ERROR!! Assert " << #x << " failed\n"; \
				cout << " on line " << __LINE__  << "\n"; \
				cout << " in file " << __FILE__ << "\n";  \
			}
#endif

//Using:
int x=5;

ASSERT(x==5); // TRUE == do nothing
x=6;
ASSERT(x==5); // FALSE == print error message
Linked List
A linked list is a chain of objects which are linked together with pointers - each object points to the next object.
Node - a chain element.
Head - the first node.
Tail - the last node.
The data example:
class CAT
{
public:
    CAT() { itsAge = 1;}
    CAT(int age):itsAge(age){}
    ~CAT(){};
    int GetAge() const { return itsAge; }
private:
    int itsAge;
};

// linked list element
class Node
{
public:
    Node(CAT * pCat);
    ~Node();
    void SetNext(Node * pnode) { pitsNext = pnode; }
    Node * GetNext() const { return pitsNext; }
    CAT * GetCat() const { return pitsCat; }
    void Insert(Node * pnewNode);
    void Display();

private:
    CAT * pitsCat;
    Node * pitsNext; // pointer to a next node
};

Cat		Cat		Cat			
							
pitsCat		pitsCat		pitsCat			
pitsNext		pitsNext		pitsNext		NULL	

Casting Down - Dynamic_cast
Run Time Type Identification (RTTI) - compiler is able to identify the object type which the pointer is pointing to.
This is called casting down, because you are casting the Horse object down to a more derived type.
If you have a pointer to a base class such as Horse, and you assign to it a pointer to a derived class, such as Pegasus, you can use the Horse pointer polymorphically. If you then need to get at the Pegasus object, you create the Pegasus pointer and use the dynamic_cast operator to make the conversion.
At runtime, the base pointer will be examined. If the conversion is proper, your new Pegasus pointer will be fine. If the conversion is improper, if you didn't really have a Pegasus object after all, then your new pointer will be NULL. 
The expression dynamic_cast<type-id>( expression ) converts the operand expression to an object of type type-id.
class Horse
{
public:
    virtual void Gallop(){ cout << "Galloping...\n"; }
...

class Pegasus : public Horse
{
public:
    virtual void Fly() { cout << "I can fly! I can fly! I can fly!\n"; 
...

// using:
enum{MAXHORSES=2};
Horse * pRanch[MAXHORSES];
Pegasus * pPeg;
int i;

pRanch[0] = new Horse;
pRanch[1] = new Pegasus;
for (i=0;i<MAXHORSES;++i)
{
    pPeg = dynamic_cast< Pegasus *> (pRanch[i]);
    // Dynamic casting:
    //    if expression () is a pointer to Pegasus then 
    //        return pointer to Pegasus
    //    if not then return NULL pointer
...
NOTE: DO avoid switching on the runtime type of the object--use virtual functions, templates, and multiple inheritance.
Modular Programming
The good programming practice is to put classes declarations to a header file and class functions definitions put into a source file.
Interface / Implementation
Interface - the declaration of the class - it tells the user how to interact with the class.
Implementation - the function (method) definition.
Naming conventions:
*.HPP	header file for C++, classes declarations -- interface
*.CPP	source file for C++, the definitions of the class functions
Header File
Header file - CPP03class.hpp:
//-----------------------------------------------------------
// CPP03class.HPP - CPP language learning - classes - header
//-----------------------------------------------------------

#include <iostream.h>

class Cat // CLASS == TYPE
{
public:  // PUBLIC MEMBERS
    Cat(int initAge)         // CONSTRUCTOR - mustn't have a return type!
        { catAge=initAge; }
    ~Cat() { }               // DESTRUCTOR - mustn't have a return type!

    int GetAge() const       // public ACCESSOR method (function)
        { return(catAge); }  // GetAge - obtain a cat age--inline function
    void SetAge(int age); 
    void Meow(void) const;
private: // PRIVATE MEMBERS
    int catAge;            // PRIVATE DATA
};
Main source file - CPP03class.cpp:
//-----------------------------------------------------
// CPP03 - CPP language learning - classes 
//-----------------------------------------------------

#include <iostream.h>
#include "CPP03class.hpp"

//=== IMPLEMENTATION ================================================

//***************************************
// SetAge - set a cat age
//***************************************
void Cat::SetAge(int age) // method SetAge is a member of the class Cat
{
    catAge=age; 
}

//***************************************
// Meow - let a cat meowing
//***************************************
void Cat::Meow() const  // const == you won't be able to change the class data
{
    cout << "Meeooooow, aaaaggrrrr\n";
}

//=== MAIN =========================================================
void main()
{
    Cat Frisky (5); // INSTANCE == OBJECT == VARIABLE

    // CLASS access
    cout << "Frisky's age = " << Frisky.GetAge() << endl;
    cout << "Meowing test : ";
    Frisky.Meow();
}

C++ overview
Functions (Methods) Declaration Overview

Feature	Description	
default parameters	You can initialize a function parameter with a default value.
void MyFun(int Param1, int Param2=1, int Param3=4);
After that you can have variable number of parameters.
void MyFun(10);	
overloading
(polymorphism)	More functions with the same name - must differ in number or type of parameters.
int   MyFun(int x, int y);
float MyFun(float x, float y, float z);	
const	Const function == read-only == you promise no change for member data.
int GetAge() const{ return(itsAge); }	
init members	The constructor can have the initialization stage for data members.
Cat(int age,int weight):catAge(age), catWeight(weight) {}	
copy constructor	Copy constructor is called by object copying during another object creating.
Cat(const Cat & rhs){...} // definition
Cat Johny(Friskie);  // calls COPY CONSTRUCTOR	
Operators Overloading Overview

Feature	Description	
operator overloading	When you overload operators (=, +, [], ...), you can use them  directly with class.
Cat & operator=(const Cat & rhs){ ... }
Counter operator+ (const Counter & rhs) { ... }; //"+" 
char & operator[](unsigned short offset); // write data
char operator[](unsigned short offset) const; //READ-ONLY
const Counter & operator++ () { ... }    // PREFIX ++
const Counter   operator++ (int) { ... } // POSTFIX ++	
conversion operator	Conversion between class data member <-> fundamental types (int, char, ...)
// class_member <- int - constructor with init
Counter(int initVal):countVal(initVal){ }; // definition
Counter count1 = 4; // call
// int <- class_member - operator int()
operator int(){ return countVal; }; // definition
int x = count1;	

Pointers, References, Arrays Overview

Feature	Description	
array	Array of objects:
Cat CatArray[5]; // definition - constructor called 5 x
CatArray[0].GetAge(); // class access	

Feature	Description	
new,
delete	Allocates / frees memory for object. 
// --- Pointer to Object ---
Cat * pCat = new Cat(5); // 1 Cat, CONSTRUCTOR with init
if (pCat==NULL) ...  // successful memory allocation test
pCat->SetAge(1);         // function call
delete pCat;             // 1 Cat, DESTRUCTOR call
pCat=NULL;               // wild pointer protection	
	// --- Pointer to ARRAY of Objects ---
//4 x Cat, 4 x default CONSTRUCTOR call, NOT ALLOWED INIT
Cat * paCat = new Cat[4];
paCat[0].SetAge(2);   // function call - pointer to array
delete [] paCat;         // 4 x Cat, 4 x DESTRUCTOR call	
	// --- ARRAY of Pointers to Object ---
// NO memory allocation, NO CONSTRUCTOR call
Cat * paaCat[4];
//4 x Cat, 4 x CONSTRUCTOR with INIT call
for (xp=0;xp<4;++xp) paaCat[xp] = new Cat(1);
paaCat[0]->SetAge(3); // function call - array of pointers
// 4 x Cat, 4 x DESTRUCTOR call
for (xp=0;xp<4;++xp) delete paaCat[xp]; 	
this	this pointer points to object from its inside (also when the object isn't created by new).
int GetAge() const { return this->catAge; }	
& (reference)	Symbolic name with the same memory address as the target.
int X;
int & refX = X; // reference to variable X	
Derivation (Inheritance) Overview

Feature	Description	
derivation
(inheritance)	The derived class inherits the functionality of the base class.
class Cat : public Mammal // DERIVATION
Cat::Cat():Mammal(), ... // explicit constructor call
Cat Friskie;       // Mammal constructor(own memory part)
                   // Cat constructor
/* out of scope */ // Cat destructor
                   // Mammal destructor	
virtual,
overriding	Virtual function - a function in a base class that you expect to be overrided. The used variable must be a pointer or a reference!
The destructor must be virtual too!
Overrided function - a function in a derived class with the same name and the head as a function in a base class.
// Base_class - virtual function definition
virtual void Function1();
// Derived_class - function overriding
void Function1(); 
// Using: pointer definition
Base_class * pBase_class = new Derived_class; 
// Using: calls Derived_class.Function1()
pBase_class->Function1();	

Controlling Access to Class Members - PRIVATE, PROTECTED, PUBLIC

Type of Access	Access allowed for:	
private	internal member functions, friends	
protected	internal member functions, friends, derived class	
public	any function	
Controlling Access through Derivation - PRIVATE, PROTECTED, PUBLIC

Member Access in Base Class	Derivation Type	Access from derived class:	
private	no matter	always inaccessible	

protected	private	private	
	protected	protected	
	public	protected	

public	private	private   (next derivation - NO ACCESS)	
	protected	protected	
	public	public	
Specialities Overview

Feature	Description	
qualified call	Fully qualifying calling:
object_name.base_class_name::function_name();
Friskie.Mammal::Sound();   // object
pFriskie->Mammal::Sound(); // pointer	
Abstract Data Type (ADT)	A base, abstract concept class. Not allowed to make an object! Changing a class to ADT - use pure virtual function. All pure virtual functions must be overridden (or you will have an ADT again)!
virtual void Run() = 0 { }    // pure virtual function	
static members	A static member is one per class, belongs to the class not to the object. Static member functions have access only to a static member variables!
// Static Member Data
static int XCats; // declaration - no memory allocation
int Cat::XCats = 0; // definition - memory allocation 
i = Cat::XCats; // using - class::static_data
// Static Member Function
static int GetHowMany() { return XCats; }
i = Cat::GetHowMany(); // call - without object	
friend class

friend function	A friend class definition - your private data access establishing.
class C10
{
    friend class C20;
friend void C20::C21public();	

Class Declaration Overview

class Cat : public Mammal // DERIVATION
{
public:  // --- PUBLIC members ----------------------------------------
    // --- CONSTRUCTORS part ------------
    Cat():itsAge(1){ }                // default CONSTRUCTOR
    Cat(int initAge):itsAge(initAge){ }    // CONSTRUCTOR with init part
    Cat(const Cat & rhs);                  // COPY CONSTRUCTOR
    ~Cat(){}                               // DESTRUCTOR

    // --- OPERATORS OVERLOADING part ---------------
    Cat & operator=(const Cat & rhs)
        { itsAge = rhs.GetAge(); return *this; } // = operator overloading
    operator int(){ return(itsAge); }; // Conversion operator

    // --- ACCESSORS part ---------------
    int GetAge() const{ return(itsAge); }  // ACCESSOR function (function)
    void SetAge(int newAge) { itsAge = newAge; }

    // --- Other functions part -----------
    virtual void Speak()const{ }  // Virtual function
    virtual void Run() = 0 { }    // Pure Virtual function

protected:
private: // --- PRIVATE members ---------------------------------------
    int itsAge; // private data
    static int HowManyCats; // static member data declaration
};

int Cat::HowManyCats = 0; // definition

//***************************************************
// Copy Constructor - function definition
//***************************************************
Cat::Cat(const Cat & rhs)
{
    itsAge = rhs.GetAge();
}

//*********************************
// ClassTest - class functions test
//*********************************
void ClassTest()
{
    Cat Friskie(3);      // calls CONSTRUCTOR with init
    Cat Johny(Friskie);  // calls COPY CONSTRUCTOR
    Cat Sammy = Friskie; // calls COPY CONSTRUCTOR variant 2
    // without Copy Constructor declaration - calls default
    // Copy Constructor == hard copy 1:1
    
    Johny.SetAge(5);     // calls function
    Friskie = Johny;     // call = Equal operator overloading
    // without Equal operator overloading - calls default
    // Equal operator == hard copy 1:1

} // end of scope - calls DESTRUCTORs

C overview
VARIABLES

Type Name	Bytes	Other Names	Range of Values	
int	*	signed, signed int	System dependent	
unsigned int	*	unsigned	System dependent	
char	1	signed char	-128 to 127	
unsigned char	1	none	0 to 255	
short	2	short int
signed short int	-32,768 to 32,767	
unsigned short	2	unsigned short int	0 to 65,535	
long	4	long int
signed long int	-2,147,483,648 to 2,147,483,647	
unsigned long	4	unsigned long int	0 to 4,294,967,295	
enum	2	none	-32,768 to 32,767	
float	4	none	3.4E +/- 38 (7 digits)	
double	8	none	1.7E +/- 308 (15 digits)	
long double	10	none	1.2E +/- 4932 (19 digits)	
* (pointer)	4	none	seg 0 to 65,535 : offset 0 to 65,535	
CONST - Constants

type	Initialization	
char	'A'	
string	"text"	
integer	1234u or U - unsigned
1234l or L - long	
hexadecimal	0x2F	
float	12.34f or F
-25E-4 = -0.0025	
long double	12.34l or L	
array	[2][3]={{1,2,3},{4,5,6}};
[2][10]={"John","Michael"};	
struct	struct guns pistol={"Uzi",30,7};	
Symbolic Constant

#define  MAXARRAY  100    /* GLOBAL - for whole program */enum{MAXARRAY=100};       /* LOCAL */
Type Manipulation - TYPEDEF, Type-casting

typedef char mychartype; /* new type definition */
mychartype nextchar;     /* using */

floatnumber=(float)integernumber;   /* type-casting (forcedtype)variable*/
Type conversions
•	If one of operands in an expression is of MASTER type, the other operand (SLAVE) is converted to the proper type. Priority 1 is the highest - it is searched first.

Priority	MASTER type	SLAVE type	SLAVE conversion	
1	long double	any	long double	
2	double	any	double	
3	float	any	float	
4	unsigned long	any integer	unsigned long	
5	long	unsigned int	unsigned long	
6	long	any integer	long	
7	unsigned int	any integer	unsigned int	
8	any integer	any integer	int	
OPERATORS
Increment
Pre-fix: ++x means incrementing is BEFORE using:
Post-fix: x++ means incrementing is AFTER using:
Comparison operators

Operator	Meaning	
==	equal	
!=	not equal	
>	greater than	
<	less than	
>=	gtreater or equal than	
<=	less or equal than	
Logical operators

Operator	Meaning	
&&	AND	
||	OR	
!	NOT	
The value of a logical expression evaluation:
TRUE  != 0
FALSE == 0
Bitwise operators

Operator	Meaning	
&	Bitwise AND	
|	Bitwise OR	
^	Bitwise XOR	
<<	Left shift	
>>	Right shift	
~	Negation all bits	

Miscellaneous

Operator	Meaning	
(type)	Type cast	x=(int)y;	
sizeof	Size of object 	x=sizeof(y);	
%	Modulus - rest after integer dividing.	x=10%3; /* x==1 */	
.	Structure (record) member	rec.mem	
->	Pointer to structure member	
,	Sequential evaluation	
Order of Precedence

Symbol	Type of Operation	Annotations	
()   []   –>   .	Expression	->  pointer to structure member	
!   ~   ++   ––
sizeof   (type)
&   *   +   –	Unary	!   NOT (logical)
~   negation all bits (bitwise)
(type)   type cast
&   address of an object
*   pointer	
*   /   %	Multiplicative	%   modulus - rest after integer dividing	
+   –	Additive		
<<   >>	Bitwise shift		
<   >   <=   >=	Relational		
==   !=	Equality	!=  not equal	
&	Bitwise-AND		
^	Bitwise-exclusive-OR		
|	Bitwise-OR		
&&	Logical-AND		
||	Logical-OR		
? :	Conditional-expression		
=    *=   /=    %=
+=   –=   <<=   >>=
&=   ^=   |=	Simple and compound assignment
(right to left associativity)	x+=3;    is equal  x=x+3;	
,	Sequential evaluation		
The short table with the precedence of symbols used by declarations:
Priority	Symbol	Note	
1	()	left to right associativity	
2	[]	left to right associativity	
3	*	right to left associativity	
The short table with the precedence of symbols used by arithmetic operations:
Priority	Symbol	
1	++  --	
2	*   /    %	
3	+   -	
The short table with the precedence of symbols used by relational operations:
Priority	Symbol	
1	<   >   <=   >=	
2	==  !=	
3	&&	
4	||	
STATEMENTS

Statement	Description	
if
else	if (expression)
	statement1;
else
	statement2;	
switch	switch (expression) 
{
    case const1: statement1; break;
    ...
    case constx: statementx; break;
    default:     statement;  break;
}	
for	for (init_expression;cond_expression;loop_expression)
    statement;	
break	Terminates the loop without evaluation loop_expression.	
continue	Causes a jump to the start and evaluation loop_expression.	
while	while (expression)
    statement;	
do - while	do
    statement;
while (expression);	
{ }	Block (compound statement).
{
    statement1;
    statement2;
}	
ADVANCED DATA TYPES

Data type	Description	
array	int multi[2][3] = { {00,01,02}, {10,11,12} };/* INIT */	
string	unsigned char sa[]="abc";	
struct	struct type_name
{
    type variable_name1;
    type variable_name2;
} structure_variable;
struct type_name structure_variable;	
union	union type_name
{
    type variable_name1;
    type variable_name2;
} union_variable;	
bit field	struct 
{
    unsigned short      icon : 8; /* 8 bits field */
    unsigned short     color : 4;
    unsigned short underline : 1;
    unsigned short     blink : 1;
} screen;	
enum	enum type_name{ name1, name2=init_val } enum_variable;	

Multidimensional arrays

enum {ROWS=3,COLS=3};
int multi[ROWS][COLS] = { {00,01,02}, {10,11,12}, {20,21,22} }; /* INIT */
Logical representation:
      ┌────┬────┬────┐
row 2 │ 20 │ 21 │ 22 │
      ├────┼────┼────┤
row 1 │ 10 │ 11 │ 12 │
      ├────┼────┼────┤
row 0 │ 00 │ 01 │ 02 │
      └────┴────┴────┘
column   0    1    2
Memory representation:
        │<─  row 0   ─>│<─  row 1   ─>│<─  row 2   ─>│
        ┌────┬────┬────┬────┬────┬────┬────┬────┬────┐
        │ 00 │ 01 │ 02 │ 10 │ 11 │ 12 │ 20 │ 21 │ 22 │
        └────┴────┴────┴────┴────┴────┴────┴────┴────┘
offset     0    1    2    3    4    5    6    7    8
Pointers and Memory Representation
Variable Storing in the Memory
example : unsigned long i=257;

Memory   : Higher address                                Lower address
bits     : 31  ..  16 ┌15┬14┬13┬12╥11┬10┬09┬08┐ ┌07┬06┬05┬04╥03┬02┬01┬00┐
 content :  0  ..   0 │ 0│ 0│ 0│ 0║ 0│ 0│ 0│ 1│ │ 0│ 0│ 0│ 0║ 0│ 0│ 0│ 1│
                      └──┴──┴──┴──╨──┴──┴──┴──┘ └──┴──┴──┴──╨──┴──┴──┴──┘
bytes    : 3 - 2 byte           1 byte                    0 byte (lowest)
 content : 0x00 0x00            0x01                      0x01
address  : 0040:0023 0040:0022  0040:0021              0040:0020
Memory address structure:
          SEGMENT : OFFSET
address :   00 40 : 00 20
            Hi Lo : Hi Lo byte
Pointer Manipulation

int x=1,y=8; /* x, y == variables - containes data */
int *pointx=&x; /* int * = pointer to int */
                /* &x    = address of the variable x */ 
                /* variable pointx contains address of variable x */
                     ┌─────────┐     ┌─────────┐          ┌─────────┐
variable content : x │        1│   y │        8│   pointx │0040 0010│
                     └─────────┘     └─────────┘          └─────────┘
  memory address :    0040:0010       0040:0020            0040:0500
Arrays and Pointers

enum {MAX=5};
int arr[MAX] = {00,01,02,03,04};
int * parr = arr;

&arr[0]==arr==parr // the same address access
   arr[3]==3       // the same data access
  parr[3]==3
*(parr+3)==3
 *(arr+3)==3

Pointer to Pointer

int val=5;
int *pval=&val;
int **ppval=&pval;

    val==5                /* stored value */
   &val==0040:0030        /* address of variable val */
  *pval==5                /* point to value */
   pval==0040:0030==&val  /* stored address of variable val */
  &pval==0040:0020        /* address of variable pval */
**ppval==5                /* point to point to value */
 *ppval==0040:0030==&val  /* point to variable pval with */
                          /* stored address of variable val */
  ppval==0040:0020==&pval /* stored address of variable pval */
 &ppval==0040:0010        /* address of variable ppval */
Next examples:
int *var[5]; /* (1) var name is (2) an array (3) of pointers */
 ^  ^ ^ ^    /* (4) to int values */
 4  3 1 2
The array brackets "[]" have higher priority than the pointer asterisk "*".
int (*var)[5]; /* Pointer to array of int values */
The parentheses "()" have higher priority than the brackets "[]".
long *var( long, long ); /* Function returning pointer to long */
The function modifiers "()" also have higher priority than the pointer asterisk "*".
long (*var)( long, long ); /* Pointer to function returning long */
File - disk representation
A variable storing on the disk:
struct rec
{
    int x;
    int y;
} rec1;

rec1.x=15;  /*  15==0x0F */
rec1.y=255; /* 255==0xFF */
/* written to the binary file */

File position: ┌00┬01┬02┬03╥04┬05┬06┬07┐
content:       │0F│00│00│00║FF│00│00│00│
               └──┴──┴──┴──╨──┴──┴──┴──┘
variable:      └     x    ┘ └    y     ┘
byte:           Lo       Hi

PRINTF - Formatting
The output string is closed in "xxx",  variable data have the format character "%":
%[flags] [width] [.precision] [prefix] type

Type	Meaning	
%c	character	
%s	string	
%d	signed integer (decimal)	
%f	double (float) - decimal notation - form "[ – ]dddd.dddd"	
%u	unsigned integer	
%X	unsigned hexadecimal integer - form "ABCD ..."	
%p	pointer to void - form "SSSSOOOO" - segment, offset in uppercase hexa	
%e	double - scientific notation - form "[ – ]d.dddd e [sign]ddd"	
%g	f or e type by decision , e is used if the exponent > 4 or <-4, zeros are truncated, the decimal point appears only when some digits folow it	

Flag	Meaning	Default	
0	zeros adding until the defined width	no prefix zeros	
-	the left align within the defined width	right align	
+	the prefix of the output value with sign +/-	only negative values sign '-'	
' '	(space) positive values will be prefixed with ' '	no space	

Width	Meaning	
1..XXX	minimum printed characters. 
If the number of characters is less, spaces are added.
If the number of characters is greater, all characters are printed (no truncated).	
*	the width specification will be supplied by argument value - variable	

Precision	Type - Meaning	
1..XXX	f - the number of digits after the decimal point. The last digit is rounded.
d - the minimum number of digits. If the number of digits is less, zeros are added to the left
s - the maximum number of characters. If the string is longer, it's TRUNCATED.	
*	the width specification will be supplied by argument value - variable	
Prefixes are only Microsoft specific, not ANSI compatible.

Prefix	Type	Meaning	
l	d,u	long int	
h	d,u	short int	

Escape Sequences

Esc seq	Meaning	
\n	new line	
\r	carriage return	
\f	form feed	
\t	tab	
\'	single quotation	
\"	double quotation	
\\	backslash	
\?	question mark	
\xhhh	ASCII char in hexa notation	
\a	Alert = Bell	

GLOSSARY

A
Abstract Data Type (ADT) - represents a concept (like Shape class) rather than an object (like Circle). In C++, an ADT is always the base class to other classes, and it is not valid to make an instance of an ADT. See pure virtual function.
argument  A value in a function calling.
array element  One item of an array.
B
base class  Mother class for derivation (inheritance). See derivation.
C
camel notation  Separate words by capitals (nameNameName - boxPointGroup).
catch block  Is the block immediately following a try block, in which exceptions are handled. See exception, try, throw.
class  (is equal to type) It takes up no room in the memory.
client  A client of your class - the parts of the program that use the class.
const member functions  If you declare a class function const, you are promising that the function won't change the value of any of the members of the class.
constructor  A special member method for data members initializating and memory allocating. The constructor can take parameters as needed, but it has no return value. Name is the same as the class name.
copy constructor  The copy constructor is called every time a copy of an object is made during another object creating. When you create an object and you use another object as init value, the copy constructor is called. When you pass an object by value as an argument of a function, or as a return value, a temporary copy of that object is made and the copy constructor is called. See shallow copy, deep copy.
D
declaration  (forward prototyping) You can declare a prototype of a function (function header) before a basic definition.
deep copy  Copies the values allocated on the heap to newly allocated memory. See shallow copy.
default parameter  You can initialize a parameter of a function with a default value.
definition  Full definition of the function with the body.
delete  The delete operator frees the allocated memory.
derivation (inheritance)  A class which adds a new functionality to an existing class is said to derive from that original class. The original class is said to be the new class's base class. The derived class inherits the functionality of the base class.
destructor  A special member method for data cleaning and memory deallocating. The destructor takes no parameters and has no return value. His name is composed by "~"+class_name.
dynamic binding  See run-time binding.
E
encapsulation  Data (variables) and functions are collected to one object.
exception  Is a predictable problem such as running out of resources (memory or disk space). In C++ is an exception also an object that is passed from the area of code where a problem occurs to the part of the code that is going to handle the problem. See try, catch, throw.
F
fence post error  Writing data paste the end of an array.
friend classes  If you want to expose your private member data or functions to another class, you must declare that class to be a friend. Friendship cannot be transferred -- friendship defining is only for two classes (no next inheritance). Friendship is not valid in reverse -- when a class A is a friend of a class B, then the class B is not automatically a friend of the class A.
H
heap  Free memory store.
I
implementation  The function definition (function body). See definition.
inheritance  See derivation.
inline function  The inline function definition causes that the compiler includes the function content (all code) instead of function calling.
instance  An object is an individual instance of a class.
interface  The declaration of the class - it tells the user how to interact with the class. See implementation.
L
linked list  Is a chain of objects which are linked together with pointers - each object points to the next object.
M
member  A variable or a function defined as a part of a class. The variable is called as the member variable, or the data member.
member-wise copy  See shallow copy.
memory leak  The pointer went out of scope, but the memory wasn't freed. You have occupied memory without any pointer.
method  A function in the class is called as a member function, or a method.
multiple inheritance  Deriving a new class from more than one base class.
N
new  The new operator allocates a part of memory of the defined size.
node  A chain element of a linked list. See linked list.
null pointer  Pointer == 0000:0000.
O
object  (is equal to variable) It takes up room in the memory. See instance.
operator overloading  You can use operators (=, +, [], ...) directly with class by operator meaning overloading.
overloading  (polymorphism) You can create more than one function with the same name. The functions must differ in their parameter list, with a different type of parameter, a different number of parameters, or both. The return type can be the same or different.
overriding  A derived class creates a function with the same return type and signature as a member function in the base class, but with a new implementation -- the same head, the different body.

P
parameter  A symbolic name in a function definition (the parameter is the local variable).
parameters passed by address using pointers  The memory address of the argument is copied to an internal variable == pointer. Changing of the parameter change directly the argument variable.
parameters passed by address using reference  The compiler uses the reference - the alias name of the original variable - which is in fact an address of the original variable.
parameters passed by value  The value in the argument is copied to an internal variable (located in the stack). Changing of the parameter inside of the function, doesn't have effect on the argument variable.
polymorphism  See overloading.
private  Private members can be accessed only within methods of the class itself. See public.
protected  Protected members are fully visible to derived classes, but are otherwise private. See private, public.
public  Public members can be accessed from outside of the class. See private.
public accessor method  Is a class member function used to read and to set the value of a private class member variable.
pure virtual functions  is made pure by initializing it with zero. Any class with one or more pure virtual functions is an ADT (Abstract Data Type), and it is illegal to instantiate the object of the class. See Abstract Data Type.
R
reference  Is an alias - an another name for the same target object.
run-time binding (dynamic binding)  A pointer is bound with an object and functions at runtime, not at compile time. 
S
shallow copy  (member-wise copy) Copies the member pointer variables 1:1. It can lead to a disaster, when the original is deleted, then the copy pointed to undefined memory space, this is stray pointer. See deep copy.
signature  The signature of a function is its name, and the number and type of its parameters. See overriding.
static member variables  Are shared among all instances of a class. Static members are one per class. They belong to the class, not to the object.
stray pointer  (dangling pointer) Using pointer without assigned memory -- after delete.
T
template  A set of parametrized classes or functions.
this pointer  Every class member function has a hidden parameter: the this pointer. this points to the individual object - the instance of the class (also when the object isn't created by new).
try block  Is a block surrounded by braces in which an exception may be shown. See exception, catch, throw.
throw  Return from a function with an exception test, jump to catch block. See exception, try, catch.
V
virtual function (method)  Is a function that you expect to be redefined in derived classes. When you refer to a derived class object using a pointer or a reference to the base class, you can call a virtual function for that object and execute the derived class's version of the function. See derivation.
virtual function table (v-table)  A table of references to virtual functions. One v-table is per class. See virtual function, virtual table pointer.
virtual table pointer (v-pointer, vptr)  Pointer to v-table. One v-pointer is per object. See virtual function, virtual function table.
W
white space  A character that is ignored by compiler -- space, tab, new line.
wild pointer  Not initialized pointer.

INDEX

A
Abstract Data Type (ADT), 21
Argument, 2
Array, 14
array of objects, 14
array of pointers to object, 15
arrays and pointers, 14
pointer to array of objects, 15
ASSERT, 37
B
Base class, 17
BOOL, 2
C
Camel notation, 1
CATCH, 34
CIN, 28
Class, 3
base class, 17
client, 4
CONST, 6
constructor, 5
derivation, 17
destructor, 5
encapsulation, 3
friend, 27
inheritance, 17
instance, 4
member, 3
member access, 4
method, 3
object, 4
PRIVATE, 4
PROTECTED, 18
PUBLIC, 4
public accessor method, 4
Client, 4
CONST, 6
Constructor, 5
copy, 11
deep copy, 11
initialization stage, 11
member-wise copy, 11
overloading, 11
shallow copy, 11
Conversion operator, 13
Copy constructor, 11
COUT, 28
D
Declaration, 2
Deep copy, 11
Default parameters, 3
Definition, 2
DELETE, 7
Derivation, 17
Destructor, 5
Dynamic binding, 20
Dynamic_cast, 38
E
Encapsulation, 3
Exceptions Handling, 34
CATCH, 34
THROW, 34
TRY, 34
Extraction operator, 2, 30
F
Fence post error, 14
Friend Classes, 27
Function
argument, 2
declaration, 2
default parameters, 3
definition, 2
header, 2
implementation, 5
overloading, 3
overriding, 19
parameter, 2
passing by address using pointers, 2, 9
passing by address using reference, 9
passing by value, 2, 9
pure virtual, 22
signature, 19
variable number of parameters, 3
virtual, 19
H
Header, 2
Heap, 14
I
Implementation, 5
Indent, 2
Inheritance, 17
Initialization stage of constructors, 11
Inline, 6
Insertion operator, 2, 30
Instance, 4
Interface, 39
iostream, 29
L
Linked list, 37
M
Member, 3
Member access, 4
Member-wise copy, 11
Memory leak, 7
Method, 3
Multiple Inheritance, 24
N
NEW, 7
Null pointer, 7
O
Object, 4
Operator
conversion, 13
extraction, 2
insertion, 2
overloading, 12
Operator overloading, 12
Overloading, 3, 11
Overriding, 19
P
Parameter, 2
Passing by address using pointers, 9
Passing by address using reference, 9
Passing by value, 9
Pointer
DELETE, 7
memory leak, 7
NEW, 7
null, 7
safety, 7
stray, 7
THIS, 8
wild, 7
Polymorphism, 3
PRIVATE, 4
Private Derivation, 26
PROTECTED, 18
PUBLIC, 4
Public accessor method, 4
Pure Virtual Function, 22
R
Reference, 9
rhs - right-hand side, 12
Run Time Type Identification (RTTI), 38
Run-time binding, 20
S
Shallow copy, 11
Signature, 19
STATIC Member Data, 22
STATIC Member Functions, 23
Stray pointer, 7
Streams, 28
String class, 15
T
Template, 35
THIS, 8
THROW, 34
TRY, 34
V
Variable number of parameters, 3
Virtual function (method), 19
Virtual Function Table (v-table), 20
Virtual Inheritance, 25
Virtual Table Pointer (v-pointer, vptr), 20
W
White space, 2
Wild pointer, 7