80

help

Welcome to the Neurillion C++ Primer!

The Neurillion C++ Primer is a free resource from Neurillion released under a Creative Commons Attribution 3.0 License. This primer was written to be a reference for the author and comes with no warranty or guarantee (see disclaimer). Information in this primer may be out of date, incorrect and possibly even dangerous. Please see the FAQ and help sections for more information and a proper disclaimer.

/*  Sat Jul 21 12:05:03 EDT 2007, v0.01 sdy gcc 4.1.2

Q:  What are C++ reserved words?

  auto      break   case    char    const   continue  default  do     double    else
  enum      extern  float   for     goto    if        int      long   register  return
  short     signed  sizeof  static  struct  switch    typedef  union  unsigned  void
  volatile  while


new c++ words not in/from c:

  asm        bool     catch      class   const_cast        delete       dynamic_cast
  explicit   false    friend     inline  mutable           namespace    new
  operator   private  protected  public  reinterpret_cast  static_cast  template
  this       throw    true       try     typeid            typename     using
  virtual    wchar_t



additional c++ words:

  and  and_eq  bitand  bitor  compl  not  not_eq  or  or_eq  xor  xor_eq


This is what the primer looks like.  

*/

//  simple
void f1(char c, int i, float f, double d);
void f2(short int si, long int li, long double ld);
void f3(unsigned char uc, unsigned int ui,  unsigned short int usi, unsigned long int uli);

//  pointer
void f4(char* cp, int* ip, float* fp, double* dp);
void f5(short int* sip, long int* lip, long double* ldp);
void f6(unsigned char* ucp, unsigned int* uip, unsigned short int* usip, unsigned long int* ulip);

//  reference
void f7(char& cr, int& ir, float& fr, double& dr);
void f8(short int& sir, long int& lir, long double& ldr);
void f9(unsigned char& ucr, unsigned int& uir, unsigned short int& usir, unsigned long int& ulir);

//  simple / short C++ program that uses every C++ reserved word


















stdlib

/*

The Standard C++ library consists of 51 required headers.
13 constitute the Standard Template Library, or STL.

c++ standard

The Standard C++ libraries:

*/

#include <algorithm>   //  STL:  algorithms such as: 
#include <bitset>      //  sets of bits
#include <complex>     //  complex numbers and arithmetic
#include <deque>       //  container:  deque
#include <exception>   //  exception handling
#include <fstream>     //  iostream templates for working with files
#include <functional>  //  STL:  templates to work with  and 
#include <iomanip>     //  iostreams
#include <ios>         //  base clasee for some iostream classes
#include <iosfwd>      //  forward declarations of iostream classes
#include <iostream>    //  standard I/O streams
#include <istream>     //  istreams ( in )
#include <iterator>    //  STL:  iterators
#include <limits>      //  numeric type properties
#include <list>        //  STL:  template class for doubly linked list container
#include <locale>      //  locale-specific behavior
#include <map>         //  STL:  container-  tie/map key to value
#include <memory>      //  STL:  memory templates
#include <new>         //  for   memory functions
#include <numeric>     //  STL:  various numeric functions
#include <ostream>     //  ostreams ( out )
#include <queue>       //  STL:  container- queue
#include <set>         //  STL:  container- associative
#include <sstream>     //  sstreams ( uses string as container )
#include <stack>       //  STL:  container- stack
#include <stdexcept>   //  standard exceptions
#include <streambuf>   //  buffer iostreams operations
#include <string>      //  standard strings ( container )
#include <strstream>   //  iostreams classes that work with strings as their container
#include <typeinfo>    //  for use with typeid
#include <utility>     //  STL:  several templates of general utility
#include <valarray>    //  value arrays
#include <vector>      //  STL:  Container- vector ( like a resizable array )

new C style

/*

  The Standard C++ library also works along with the 18 headers from the
  Standard C library.  C++ style C headers are:

*/

#include <cassert>  //  for enforcing assertions when functions execute
#include <cctype>   //  for classifying characters
#include <cerrno>   //  for testing error codes reported by library functions
#include <cfloat>   //  for testing floating-point type properties
#include <ciso646>  //  for programming in ISO 646 variant character sets
#include <climits>  //  for testing integer type properties
#include <clocale>  //  for adapting to different cultural conventions
#include <cmath>    //  for computing common mathematical functions
#include <csetjmp>  //  for executing nonlocal goto statements
#include <csignal>  //  for controlling various exceptional conditions
#include <cstdarg>  //  for accessing a varying number of arguments
#include <cstddef>  //  for defining several useful types and macros
#include <cstdio>   //  for performing input and output
#include <cstdlib>  //  for performing a variety of operations
#include <cstring>  //  for manipulating several kinds of strings
#include <ctime>    //  for converting between various time and date formats
#include <cwchar>   //  for manipulating wide streams and several kinds of strings
#include <cwctype>  //  for classifying wide characters

old C style

/*

  The normal (ie: old)  Standard C library header files are the folloring.
  WARNING:  These are deprecated and should no longer be used.

*/

#include <assert.h>  //  for enforcing assertions when functions execute  //=
WARNING: deprecated!
#include <ctype.h> // for classifying characters #include <errno.h> // for testing error codes reported by library functions #include <float.h> // for testing floating-point type properties #include <iso646.h> // for programming in ISO 646 variant character sets #include <limits.h> // for testing integer type properties #include <locale.h> // for adapting to different cultural conventions #include <math.h> // for computing common mathematical functions #include <setjmp.h> // for executing nonlocal goto statements #include <signal.h> // for controlling various exceptional conditions #include <stdarg.h> // for accessing a varying number of arguments #include <stddef.h> // for defining several useful types and macros #include <stdio.h> // for performing input and output #include <stdlib.h> // for performing a variety of operations #include <string.h> // for manipulating several kinds of strings #include <time.h> // for converting between various time and date formats #include <wchar.h> // for manipulating wide streams and several kinds of strings #include <wctype.h> // for classifying wide characters

stl

/*

The STL include files are:

*/

#include <algorithm>   //  STL:  algorithms such as: 
#include <functional>  //  STL:  templates to work with  and 
#include <iterator>    //  STL:  iterators
#include <list>        //  STL:  template class for doubly linked list container
#include <map>         //  STL:  container-  tie/map key to value
#include <memory>      //  STL:  memory templates
#include <numeric>     //  STL:  various numeric functions
#include <queue>       //  STL:  container- queue
#include <set>         //  STL:  container- associative
#include <stack>       //  STL:  container- stack
#include <utility>     //  STL:  several templates of general utility
#include <vector>      //  STL:  Container- vector ( like a resizable array )

boost

/*

Boost provides free peer-reviewed portable C++ source libraries.

We emphasize libraries that work well with the C++ Standard
Library. Boost libraries are intended to be widely useful, and usable
across a broad spectrum of applications. The Boost license encourages
both commercial and non-commercial use.

We aim to establish "existing practice" and provide reference
implementations so that Boost libraries are suitable for eventual
standardization. Ten Boost libraries are already included in the C++
Standards Committee's Library Technical Report ( TR1) as a step toward
becoming part of a future C++ Standard. More Boost libraries are
proposed for the upcoming TR2.



Q001: What is Boost?
A001: Boost is it!

*/

concepts

/*

This section of the primer deals with terminology related to C++.

inline

Inlining a function saves the "push" and "pop" to the stack for params to the function as well as the return address. Inlining causes a program to become larger due to multiple copies of the inline code -- but the trade off is execution speed (unless the increase in size of the program causes it to thrash). Typically, inline functions are small. The function's definition (the part between the {...}) must be placed in a header file,
NOTICE
unless the function is used only in a single .cpp file. An "unresolved external" occurs if an inline function is in one .cpp file and is called from another .cpp file. Declaring a function as inline is only a request to the compiler.
NOTICE
The compiler may or may not inline any or all of the calls to the inline function. There is no standard way to force a function to be inline -- other than writing the function itself where the call would have been. There may be various non-standard ways such as compiler extensions, etc.

named parameter

named parameter idiom friend

named parameter

// A macro that returns the absolute value of i #define unsafe(i) \ ( (i) >= 0 ? (i) : -(i) ) // An inline function that returns the absolute value of i inline int safe(int i) { return i >= 0 ? i : -i; } int f(); void userCode(int x) { int ans; ans = unsafe(x++); // Error! x is incremented twice ans = unsafe(f()); // Danger! f() is called twice ans = safe(x++); // Correct! x is incremented once ans = safe(f()); // Correct! f() is called once } friend method chaining

reference

class File; class OpenFile { public: OpenFile(const std::string& filename); // sets all the default values for each data member OpenFile& readonly(); // changes readonly_ to true OpenFile& readwrite(); // changes readonly_ to false OpenFile& createIfNotExist(); OpenFile& blockSize(unsigned nbytes); ... private: friend class File; std::string filename_; bool readonly_; // defaults to false [for example] bool createIfNotExist_; // defaults to false [for example] ... unsigned blockSize_; // defaults to 4096 [for example] ... }; inline OpenFile::OpenFile(const std::string& filename) : filename_ (filename) , readonly_ (false) , createIfNotExist_ (false) , blockSize_ (4096u) { } inline OpenFile& OpenFile::readonly() { readonly_ = true; return *this; } inline OpenFile& OpenFile::readwrite() { readonly_ = false; return *this; } inline OpenFile& OpenFile::createIfNotExist() { createIfNotExist_ = true; return *this; } inline OpenFile& OpenFile::blockSize(unsigned nbytes) { blockSize_ = nbytes; return *this; } The only other thing to do is make the constructor for class File to take an OpenFile object: class File { public: File(const OpenFile& params); ... }; This constructor gets the actual parameters from the OpenFile object, then actually opens the file: File::File(const OpenFile& params) { ... }

reference

Q: What is pass by reference? Q: What is pass by pointer?

class vs struct

Q: What's the difference between a class and a struct in C++? A: A struct defaults to public. */ // simple class class class_name1 { int x; }; // is the same as class class_name2 { private: int x; }; // and a struct is: struct struct_name1 { int x; }; // which is the same as class class_name3 { public: int x; }; /* If you dissect the words of the RAII acronym (Resource Acquisition Is Initialization), you will think RAII is about acquiring resources during initialization. However the power of RAII comes not from tying acquisition to initialization, but from tying reclamation to destruction. //

tail recursion

This version is not tail-recursive since the recursive call to factorial is not the last thing in the function. */ // C style factorial via recursion: int factorial_1(int n) { if (n == 0) return 1; return n * factorial_1(n - 1); } // step 1: int factorial_2a(int n, int accumulator) { if (n == 0) return accumulator; return factorial_2a(n-1, n*accumulator); } int factorial_2(int n) { return factorial_2a(n, 1); } // step 2: // tail recursion via goto: int factorial_3a(int n, int accumulator) { loop: if (n == 0) return accumulator; else { accumulator *= n; n -= 1; goto loop; } } int factorial_3(int n) { return factorial_3a(n, 1); } /* From the goto version, we can derive a version that uses C's built-in control structures: */ int factorial_4a(int n, int accumulator) { while (n != 0) { accumulator *= n; n -= 1; } return accumulator; } int factorial_4(int n) { return factorial_4a(n, 1); } void do_factorials () { std::cout << factorial_1(4) << std::endl; std::cout << factorial_2(4) << std::endl; std::cout << factorial_3(4) << std::endl; std::cout << factorial_4(4) << std::endl; } /* See SICP for references on this ... */

void*

/*

This section of the primer has miscelleneous items that don't fit in the other sections.

declare a virtual destructor in a class if and only if that class contains at least one virtual function. 

make assignment operators return a reference to *this.

"the relative order of initialization of non-local static objects defined in different translation units is undefined" 

"Fortunately, a small design change eliminates the problem entirely. All that has to be done is to move each non-local static object into its own function, where it's declared static. These functions return references to the objects they contain. Clients then call the functions instead of referring to the objects. In other words, non-local static objects are replaced with local static objects. (Aficionados of design patterns will recognize this as a common implementation of the Singleton pattern.)" 

"because C++ specifies that when a derived class object is deleted through a pointer to a base class with a non-virtual destructor, results are undefined"


#include <algorithm>
#include <iterator>
#include <functional>

template <typename T>
void qsort(T begin, T end)
{
if (begin != end)
    {
    T middle = partition(begin, end, bind2nd(less<iterator_traits<T>::value_type>(), *begin))
    qsort(begin, middle);
    qsort(max(begin + 1, middle), end);
    }
}


Some scaffolding code for testing: 

#include <iostream>
int main()
{
  int lst[] = {1, 3, 2, 1, 2, 3, 4, 1, 0};
  int sz = sizeof(lst) / sizeof(int);
  qsort(lst, lst + sz);
  copy(lst, lst + sz, ostream_iterator<int>(cout, " "));
  return 0;
}

It's also possible to bind a reference to a function: 

int f( double ); 
int (* const pf)(double) = f; // const pointer to function
int (&rf)(double) = f; // reference to function

a = pf( 12.3 ); // use pointer 
a = (*pf)(12.3); // use pointer
a = rf( 12.3 ); // use reference
a = f( 12.3 ); // use function
a = (*rf)(12.3); // convert ref to pointer and deref
a = (*f)(12.3); // convert func to pointer and deref

template <typename T>
void swap( T &a, T &b ) {
    T temp(a);
    a = b;
    b = temp;
}
//...
int x = 1, y = 2;
swap( x, y ); // x == 2, y == 1


minimum size 
char 1 byte (8 bits) 
short int 2 bytes 
int 2 bytes 
long int 4 bytes 
float 4 bytes 
double 8 bytes 
long double 8 bytes

compile line optios for g++?
-ansi -pedantic -Wall -W -Werr

Most operators can be overloaded by a programmer. The exceptions are 

. (dot) :: ?: sizeof


================================================================================
ith the recent standardization of C++, it's useful to review some of the mechanisms included in the language for dealing with character sets. This might seem like a very simple issue, but there are some complexities to contend with. 

The first idea to consider is the notion of a "basic source character set" in C++. This is defined to be: 

all ASCII printing characters 041 - 0177, save for @ $ ` DEL
        space
        horizontal tab
        vertical tab
        form feed
        newline


or 96 characters in all. These are the characters used to compose a C++ source program. 

Some national character sets, such as the European ISO-646 one, use some of these character positions for other letters. The ASCII characters so affected are: 

[ ] { } | \


To get around this problem, C++ defines trigraph sequences that can be used to represent these characters: 

[       ??(
]       ??)
{       ??<
}       ??>
        |       ??!
        \       ??/
        #       ??=
        ^       ??'
        ~       ??-


Trigraph sequences are mapped to the corresponding basic source character early in the compilation process. 

C++ also has the notion of "alternative tokens", that can be used to replace tokens with others. The list of tokens and their alternatives is this: 

        {       <%
        }       %>
        [       <:
        ]       :>
        #       %:
        ##      %:%:
        &&      and
        |       bitor
        ||      or
        ^       xor
        ~       compl
        &       bitand
        &=      and_eq
        |=      or_eq
        ^=      xor_eq
        !       not
        !=      not_eq


Another idea is the "basic execution character set". This includes all of the basic source character set, plus control characters for alert, backspace, carriage return, and null. The "execution character set" is the basic execution character set plus additional implementation-defined characters. The idea is that a source character set is used to define a C++ program itself, while an execution character set is used when a C++ application is executing. 

Given this notion, it's possible to manipulate additional characters in a running program, for example characters from Cyrillic or Greek. Character constants can be expressed using any of: 

        \137            octal
        \xabcd          hexadecimal
\u12345678      universal character name (ISO/IEC 10646)
        \u1234          -> \u00001234


This notation uses the source character set to define execution set characters. Universal character names can be used in identifiers (if letters) and in character literals: 

        '\u1234'
        L'\u2345'


The above features may not yet exist in your local C++ compiler. They are important to consider when developing internationalized applications.

================================================================================

The operators at the top of this list are evaluated first. 

Precedence      Operators
1               ()      []      ->      .
::
                !       ~       ++      --
2               - (unary)       * (dereference)
  & (address of)  sizeof
3               ->*     .* 4               * (multiply)    /       %
5               +       -
6               <<      >>
7               <       <=      >       >=
8               ==      !=
9               & (bitwise AND)
10              ^
11              |
12              &&
13              ||
14              ? :
15              =       +=      -=      etc.
16              ,
=======
Member functions which do not modify their object should be defined as const member functions. This subsequently allows the use of these functions with const objects or with const references. As a rule of thumb it is stated here that member functions should always be given the const attribute, unless they actually modify the object's data. 

char greeting[] = "Hello";

char *p = greeting;                    // non-const pointer,
                                       // non-const data

const char *p = greeting;              // non-const pointer,
                                       // const data

char * const p = greeting;             // const pointer,
                                       // non-const data

const char * const p = greeting;       // const pointer,
                                       // const data


When what's pointed to is constant, some programmers list const before
the type. Others list it after the type but before the asterisk. There
is no difference in meaning, so the following functions take the same
parameter type:

void f1(const Widget *pw);         // f1 takes a pointer to a
// constant Widget object

void f2(Widget const *pw);         // so does f2


Many people overlook the fact that member functions differing only in their constness can be overloaded, but this is an important feature of C++ 

Declaring something const helps compilers detect usage errors. const
can be applied to objects at any scope, to function parameters and
return types, and to member functions as a whole.

Compilers enforce bitwise constness, but you should program using conceptual constness. 

When const and non-const member functions have essentially identical
implementations, code duplication can be avoided by having the
non-const version call the const version.


=======



pointer. This allows the
implementation of the whole interface to change without the need to
recompile the modules using it. This is important for providing binary
compatibility through different versions of a shared library, for
example.  idioms double dispatch

Cheshire Cat idiom or pimpl like idioms

In computer programming, an opaque pointer is a datatype that hides
its internal implementation using a pointer. This allows the
implementation of the whole interface to change without the need to
recompile the modules using it. This is important for providing binary
compatibility through different versions of a shared library, for
example.

This technique is sometimes referred as "handle classes", the "Pimpin
idiom" (for "private implementation idiom") or "Cheshire Cat",
especially among the C++ community (Eckel 2000)

compilation firewall or Cheshire Cat technique, is a "private
implementation" technique useful only in CeePlusPlus and statically
compiled languages like it..
http://c2.com/cgi/wiki?PimplIdiom - link
*/

#include<iostream>
#include<string>
#include<sstream>

//  from the c++ faq lite 39.2 ...
#include <iostream>
#include <sstream>
#include <string>
#include <stdexcept>
 
class BadConversion : public std::runtime_error {
public:
  BadConversion(const std::string& s)
    : std::runtime_error(s)
    { }
};
 
inline double convertToDouble(const std::string& s)
{
  std::istringstream i(s);
  double x;
  if (!(i >> x))
    throw BadConversion("convertToDouble(\"" + s + "\")");
  return x;
}

//  Convert int to string using stringstream
std::string
itos(int i)
{
  std::stringstream s;
  s << i;
  return s.str();
}

void
do_itos()
{
  int i = 12345;
  std::string s = itos(i);
  std::cout << s << std::endl;
}

//  Print a C string 1 char at a time using recursion, C style
void cstyle_print_forward(char *s) {
  if (*s != 0) {
    std::cout << *s;
    cstyle_print_forward(s+1);
  }
}

//  Reverse print a C string 1 char at a time using recursion, C style
void cstyle_print_reverse(char *s) {
  if (*s != 0) {
    cstyle_print_reverse(s+1);
    std::cout <<*s;
  }
}

void do_printreverse() {
  char *s = "Hello world";
  cstyle_print_forward(s);
  std:: cout << std::endl;
  cstyle_print_reverse(s);
  std::cout << std::endl;
}

// This is actually the mail program to this primer!
int main()
{
  do_itos();
  do_printreverse();
  do_factorials();
}

/*
#include <sstream>
#include <string>
using namespace std;

// string to int
string some_string;
istringstream buffer(some_string);
int some_int;
buffer >> some_int;

// int to string
int some_int;
ostringstream buffer;
buffer << some_int;
string some_string = buffer.str();
*/
			

resources

/*

TR1

TR2


from wikipedia:  http://en.wikipedia.org/wiki/C++


C++ (pronounced "see plus plus", IPA: /siː plʌs plʌs/) is a general-purpose, programming
language with high-level and low-level capabilities.[1] It is a statically typed, free-form,
multi-paradigm, usually compiled language supporting procedural programming, data abstraction,
object-oriented programming, and generic programming. Since the 1990s, C++ has been one of the most
popular commercial programming languages.[citation needed]

C++ is regarded as a mid-level language. This indicates that C++ is comprised of a combination of both
high-level and low-level language features.

Bjarne Stroustrup developed C++ (originally named "C with Classes") in 1983 at Bell Labs as an
enhancement to the C programming language. Enhancements started with the addition of classes, followed
by, among other features, virtual functions, operator overloading, multiple inheritance, templates,
and exception handling. The C++ programming language standard was ratified in 1998 as ISO/IEC
14882:1998, the current version of which is the 2003 version, ISO/IEC 14882:2003. A new version of the
standard (known informally as C++0x) is being developed.


Q001:  What is this?
A001: #include 

books
links
other

FAQ

Frequently Asked Questions Q001: q A001: a

contributors

The following people have contributed to this primer: Jon

page design

This page design was inspired by Bugs Life which is a free template from Free CSS Templates released under a Creative Commons Attribution 3.0 License. The original header photo is from PDPhoto.org. Both of these are excellent resources and are highly recommended. Thank you, Jon. The header photo currently used is from the Millenium Simulation and is used because on the macro scale it resembles the structure of neurons on the micro scale.

feedback

Please send email to

disclaimer

caveat lector -- let the reader beware. The items in this primer were collected and adapted from various sources. Absolutely no claim is made for any guarantee on the items including, but not limited to: quality, accuracy, technique, safety, security or robustness.

other primers

pending. |<==============================================================================================102==>|-----|....

hw1words

h1 words

h2words

h2 words

h3words

h3 words this is h4 cool // comment1

h4words

this is h5 cool // comment1
h5words
this is h6 cool // comment1
h6words
*/
Valid CSS!