From 89fad47a827ef9298c186eeb305648f580c5e9e0 Mon Sep 17 00:00:00 2001 From: "Nicolas P. Rougier" Date: Thu, 4 Apr 2019 05:57:32 +0200 Subject: [PATCH] Initial import --- LICENSE | 21 + Makefile | 31 + README.html | 1086 ++++++++++++++++++++++++++++++++++ README.rst | 1098 +++++++++++++++++++++++++++++++++++ exam.html | 225 +++++++ exam.rst | 240 ++++++++ exam/Makefile | 35 ++ exam/exam-1 | Bin 0 -> 8648 bytes exam/exam-1.cc | 7 + exam/exam-10 | Bin 0 -> 9016 bytes exam/exam-10.cc | 12 + exam/exam-2 | Bin 0 -> 9120 bytes exam/exam-2.cc | 15 + exam/exam-3 | Bin 0 -> 9632 bytes exam/exam-3.cc | 20 + exam/exam-4 | Bin 0 -> 9016 bytes exam/exam-4.cc | 14 + exam/exam-5 | Bin 0 -> 9840 bytes exam/exam-5.cc | 14 + exam/exam-6 | Bin 0 -> 9568 bytes exam/exam-6.cc | 20 + exam/exam-7 | Bin 0 -> 9336 bytes exam/exam-7.cc | 16 + exam/exam-8 | Bin 0 -> 8712 bytes exam/exam-8.cc | 13 + exam/exam-9 | Bin 0 -> 9528 bytes exam/exam-9.cc | 13 + page.tmpl | 8 + pygment.css | 34 ++ rst2html.py | 248 ++++++++ sources/.DS_Store | Bin 0 -> 6148 bytes sources/Makefile | 35 ++ sources/crash-course-2.1.cc | 41 ++ sources/crash-course-2.2.cc | 39 ++ sources/crash-course-2.3.cc | 62 ++ sources/crash-course-2.4.cc | 33 ++ sources/crash-course-2.5.cc | 29 + sources/crash-course-2.6.cc | 41 ++ sources/crash-course-3.1.cc | 28 + sources/crash-course-3.2.cc | 60 ++ sources/crash-course-3.3.cc | 41 ++ sources/crash-course-3.4.cc | 51 ++ sources/crash-course-3.5.cc | 38 ++ sources/crash-course-4.1.cc | 43 ++ sources/crash-course-4.2.cc | 36 ++ sources/crash-course-4.3.cc | 54 ++ sources/crash-course-4.4.cc | 55 ++ sources/crash-course-4.5.cc | 33 ++ sources/crash-course-5.1.cc | 36 ++ sources/crash-course-5.2.cc | 75 +++ sources/crash-course-5.3.cc | 40 ++ sources/crash-course-5.4.cc | 82 +++ stylesheet.css | 70 +++ 53 files changed, 4192 insertions(+) create mode 100644 LICENSE create mode 100644 Makefile create mode 100644 README.html create mode 100644 README.rst create mode 100644 exam.html create mode 100644 exam.rst create mode 100644 exam/Makefile create mode 100755 exam/exam-1 create mode 100644 exam/exam-1.cc create mode 100755 exam/exam-10 create mode 100644 exam/exam-10.cc create mode 100755 exam/exam-2 create mode 100644 exam/exam-2.cc create mode 100755 exam/exam-3 create mode 100644 exam/exam-3.cc create mode 100755 exam/exam-4 create mode 100644 exam/exam-4.cc create mode 100755 exam/exam-5 create mode 100644 exam/exam-5.cc create mode 100755 exam/exam-6 create mode 100644 exam/exam-6.cc create mode 100755 exam/exam-7 create mode 100644 exam/exam-7.cc create mode 100755 exam/exam-8 create mode 100644 exam/exam-8.cc create mode 100755 exam/exam-9 create mode 100644 exam/exam-9.cc create mode 100644 page.tmpl create mode 100644 pygment.css create mode 100755 rst2html.py create mode 100644 sources/.DS_Store create mode 100644 sources/Makefile create mode 100644 sources/crash-course-2.1.cc create mode 100644 sources/crash-course-2.2.cc create mode 100644 sources/crash-course-2.3.cc create mode 100644 sources/crash-course-2.4.cc create mode 100644 sources/crash-course-2.5.cc create mode 100644 sources/crash-course-2.6.cc create mode 100644 sources/crash-course-3.1.cc create mode 100644 sources/crash-course-3.2.cc create mode 100644 sources/crash-course-3.3.cc create mode 100644 sources/crash-course-3.4.cc create mode 100644 sources/crash-course-3.5.cc create mode 100644 sources/crash-course-4.1.cc create mode 100644 sources/crash-course-4.2.cc create mode 100644 sources/crash-course-4.3.cc create mode 100644 sources/crash-course-4.4.cc create mode 100644 sources/crash-course-4.5.cc create mode 100644 sources/crash-course-5.1.cc create mode 100644 sources/crash-course-5.2.cc create mode 100644 sources/crash-course-5.3.cc create mode 100644 sources/crash-course-5.4.cc create mode 100644 stylesheet.css diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..9092cfa --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019 Nicolas P. Rougier + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..a328056 --- /dev/null +++ b/Makefile @@ -0,0 +1,31 @@ +MAKE = /usr/bin/make +RST2HTML = ./rst2html.py +STYLESHEET = stylesheet.css +RST2HTML_OPTIONS = --strip-comments \ + --report=3 \ + --section-numbering \ + --no-toc-backlinks \ + --template=page.tmpl \ + --cloak-email-addresses \ + --stylesheet=$(STYLESHEET) \ + --link-stylesheet + +SOURCES = $(wildcard *.rst) +OBJECTS = $(subst .rst,.html, $(SOURCES)) + +all: $(OBJECTS) pygment.css + +#pygment.css: +# @pygmentize -S tango -f html > pygment.css + +%.html: %.rst Makefile + @echo " - $@" + @$(RST2HTML) $(RST2HTML_OPTIONS) $< $@ + +clean: + @-rm -f $(OBJECTS) + +distclean: clean + @-rm -f `find . -name "*~"` + +.PHONY: all home clean distclean diff --git a/README.html b/README.html new file mode 100644 index 0000000..70be87b --- /dev/null +++ b/README.html @@ -0,0 +1,1086 @@ + + + + + + +C++ crash course for C programmers + + + + +
+

C++ crash course for C programmers

+ +++ + + + + + +
Author:Nicolas P. Rougier
Sources:crash-course.rst
+ +
+

1   Foreword

+

This is an introduction to C++ for C programmers:

+
    +
  • If you can't understand the code below, you'd better start with a C tutorial.

    +
    +#include <stdio.h>
    +
    +void main (int argc, char **argv)
    +{
    +    printf("Hello World!\n");
    +}
    +
    +
  • +
  • If you don't know what are the stack and the heap, you'd better have a look at +some architecture & system introduction.

    +
  • +
  • If you know java, that might help a bit.

    +
  • +
  • If you think python is cool, you're right, but +still, this is not the place.

    +
  • +
  • If you never heard about Bjarne Stroustrup, you might be at the right place.

    +
  • +
  • Here is a list of C++ specific keywords:

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

2   From C to C++

+

Even if C++ is slanted toward object-oriented programming (OOP), you can +nevertheless use any c++ compiler to compile c code and benefits from some c++ +goodies.

+
+

2.1   Input/Output

+

Prefer the use of <iostream> for input/output operations (see stream +section for explanation).

+
+#include <iostream>
+
+int main (int argc, char **argv)
+{
+    int i;
+    std::cout << "Please enter an integer value: ";
+    std::cin >> i;
+    std::cout << "The value you entered is " << i  << std::endl;
+    return 0;
+}
+
+
+
+

2.2   New/Delete

+

The new and delete keywords are used to allocate and free memory. They +are "object-aware" so you'd better use them instead of malloc and +free. In any case, never cross the streams (new/free or malloc/delete).

+
+int *a = new int;
+delete a;
+
+int *b = new int[5];
+delete [] b;
+
+

delete does two things: it calls the destructor and it deallocates the +memory.

+
+
+

2.3   References

+

A reference allows to declare an alias to another variable. As long as the +aliased variable lives, you can use indifferently the variable or the alias.

+
+int x;
+int& foo = x;
+
+foo = 42;
+std::cout << x << std::endl;
+
+

References are extremely useful when used with function arguments since it +saves the cost of copying parameters into the stack when calling the function.

+
+
+

2.4   Default parameters

+

You can specify default values for function parameters. When the function is +called with fewer parameters, default values are used.

+
+float foo( float a=0, float b=1, float c=2 )
+{return a+b+c;}
+
+cout << foo(1) << endl
+     << foo(1,2) << endl
+     << foo(1,2,3) << endl;
+
+

You should obtain values 4, 5 and 6.

+
+
+

2.5   Namespaces

+

Namespace allows to group classes, functions and variable under a common scope +name that can be referenced elsewhere.

+
+namespace first  { int var = 5; }
+namespace second { int var = 3; }
+cout << first::var << endl << second::var << endl;
+
+

You should obtain values 3 and 5. There exists some standard namespace in the +standard template library such as std.

+
+
+

2.6   Overloading

+

Function overloading refers to the possibility of creating multiple functions +with the same name as long as they have different parameters (type and/or +number).

+
+float add( float a, float b )
+{return a+b;}
+
+int add( int a, int b )
+{return a+b;}
+
+

It is not legal to overload a function based on the return type (but you can do it +anyway)

+
+
+

2.7   Const & inline

+

Defines and macros are bad if not used properly as illustrated below

+
+#define SQUARE(x) x*x
+
+int result = SQUARE(3+3);
+
+

For constants, prefer the const notation:

+
+const int two = 2;
+
+

For macros, prefer the inline notation:

+
+int inline square(int x)
+{
+    return x*x;
+}
+
+
+
+

2.8   Mixing C and C++

+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include "some-c-code.h"
+
+#ifdef __cplusplus
+}
+#endif
+
+
+
+
+

2.9   Exercises

+
    +
  1. Write a basic makefile for compiling sources

    +

    solution: Makefile

    +
  2. +
  3. How would you declare:

    +
  4. +
+
+
    +
  • A pointer to a char
  • +
  • A constant pointer to a char
  • +
  • A pointer to a constant char
  • +
  • A constant pointer to a constant char
  • +
  • A reference to a char
  • +
  • A reference to a constant char
  • +
+

solution: crash-course-2.1.cc

+
+
    +
  1. Create a two-dimensional array of integers (size is n x n), fill it with +corresponding indices (a[i][j] = i*n+j), test it and finally, delete it.
  2. +
+
+solution: crash-course-2.2.cc
+
    +
  1. Write a function that swap two integers, then two pointers.
  2. +
+
+solution: crash-course-2.3.cc
+
    +
  1. Is this legal ?

    +
    +int add( int a, int b ) { return a+b; }
    +
    +int add( int a, int b, int c=0 ) { return a+b+c; }
    +
    +
  2. +
+
+solution: crash-course-2.4.cc
+
    +
  1. Write a const correct division function.
  2. +
+
+solution: crash-course-2.5.cc
+
    +
  1. What's the difference between int const* p, int* const p +and int const* const p ?
  2. +
+
+solution: crash-course-2.6.cc
+
+
+
+

3   Classes

+

A class migh be considered as an extended concept of a data structure: instead +of holding only data, it can hold both data and functions. An object is an +instantiation of a class. By default, all attributes and functions of a class +are private (see below Access control). If you want a public default behavior, +you can use keyword struct instead of keyword class in the declaration.

+
+class Foo {
+    int attribute;
+    int function( void ) { };
+};
+
+struct Bar {
+    int attribute;
+    int function( void ) { };
+};
+
+Foo foo;
+foo.attribute = 1; // WRONG
+
+Bar bar;
+bar.attribute = 1;  // OK
+
+
+
+

3.1   Constructors

+

It is possible to specify zero, one or more constructors for the class.

+
+#include <iostream>
+
+class Foo {
+public:
+    Foo( void )
+    { std::cout << "Foo constructor 1 called" << std::endl; }
+    Foo( int value )
+    { std::cout << "Foo constructor 2 called" << std::endl; }
+};
+
+int main( int argc, char **argv )
+{
+    Foo foo_1, foo_2(2);
+    return 0;
+}
+
+
+
+

3.2   Destructor

+

There can be only one destructor per class. It takes no argument and returns +nothing.

+
+#include <iostream>
+
+class Foo {
+public:
+    ~Foo( void )
+    { std::cout << "Foo destructor called" << std::endl; }
+}
+int main( int argc, char **argv )
+{
+    Foo foo();
+    return 0;
+}
+
+

Note that you generally never need to explicitly call a destructor.

+
+
+

3.3   Access control

+

You can have fine control over who is granted access to a class function or +attribute by specifying an explicit access policy:

+
    +
  • public: Anyone is granted access
  • +
  • protected: Only derived classes are granted access
  • +
  • private: No one but friends are granted access
  • +
+
+
+

3.4   Initialization list

+

Object's member should be initialized using initialization lists

+
+class Foo
+{
+    int _value;
+public:
+    Foo(int value=0) : _value(value) { };
+};
+
+

It's cheaper, better and faster.

+
+
+

3.5   Operator overloading

+
+class Foo {
+private:
+    int _value;
+
+public:
+    Foo( int value ) : _value(value) { };
+
+    Foo operator+ ( const Foo & other )
+    {
+        return Foo( _value+ other._value );
+    }
+
+    Foo operator* ( const Foo & other );
+    {
+        return Foo( _value * other._value );
+    }
+}
+
+
+
+

3.6   Friends

+

Friends are either functions or other classes that are granted privileged +access to a class.

+
+#include <iostream>
+
+class Foo {
+public:
+    friend std::ostream& operator<< ( std::ostream& output,
+                                      Foo const & that )
+    {
+        return output << that._value;
+    }
+private:
+    double _value;
+};
+
+int main( int argc, char **argv )
+{
+  Foo foo;
+  std::cout << "Foo object: " << foo << std::endl;
+  return 0
+}
+
+
+
+

3.7   Exercices

+
    +
  1. Why the following code doesn't compile ?

    +
    +class Foo { Foo () { }; };
    +
    +int main( int argc, char **argv )
    +{
    +    Foo foo;
    +}
    +
    +

    solution: crash-course-3.1.cc

    +
  2. +
  3. Write a Foo class with default and copy constructors and add also an +assignment operator. Write some code to highlight the use of each of them.

    +

    solution: crash-course-3.2.cc

    +
  4. +
  5. Write a Point class that can be constructed using cartesian or polar +coordinates.

    +

    solution: crash-course-3.3.cc

    +
  6. +
  7. Write a Foo class and provide it with an input method.

    +

    solution: crash-course-3.4.cc

    +
  8. +
  9. Is is possible to write something like foo.method1().method2() ?

    +

    solution: crash-course-3.5.cc

    +
  10. +
+
+
+
+

4   Inheritance

+
+

4.1   Basics

+

Inheritance is done at the class definition level by specifying the base class +and the type of inheritance.

+
+class Foo                            { /* ... */ };
+class Bar_public : public Foo        { /* ... */ };
+class Bar_private : private Foo      { /* ... */ };
+class Bar_protected : protected Foo  { /* ... */ };
+
+

Bar_public, Bar_private and Bar_protected are derived from Foo. +Foo is the base class of Bar_public, Bar_private and Bar_protected.

+
    +
  • In Bar_public, public parts of Foo are public, +protected parts of Foo are protected
  • +
  • In Bar_private, public and protected parts of Foo are private
  • +
  • In Bar_protected, public and protected parts of Foo are protected
  • +
+
+
+

4.2   Virtual methods

+

A virtual function allows derived classes to replace the implementation +provided by the base class (yes, it is not automatic...). Non virtual methods +are resolved statically (at compile time) while virtual methods are resolved +dynamically (at run time).

+
+class Foo {
+public:
+    Foo( void );
+    void method1( void );
+    virtual void method2( void );
+};
+
+class Bar : public Foo {
+public:
+    Bar( void );
+    void method1( void );
+    void method2( void );
+};
+
+Foo *bar = new Bar();
+bar->method1();
+bar->method2();
+
+

Make sure your destructor is virtual when you have derived class.

+
+
+

4.3   Abstract classes

+

You can define pure virtual method that prohibits the base object to be +instantiated. Derived classes need then to implement the virtual method.

+
+class Foo {
+public:
+    Foo( void );
+    virtual void method( void ) = 0;
+};
+
+class Bar: public Foo {
+public:
+    Foo( void );
+    void method( void ) { };
+};
+
+
+
+

4.4   Multiple inheritance

+

A class may inherit from multiple base classes but you have to be careful:

+
+class Foo               { protected: int data; };
+class Bar1 : public Foo { /* ... */ };
+class Bar2 : public Foo { /* ... */ };
+class Bar3 : public Bar1, public Bar2 {
+    void method( void )
+    {
+       data = 1; // !!! BAD
+    }
+};
+
+

In class Bar3, the data reference is ambiguous since it could refer to +Bar1::data or Bar2::data. This problem is referred as the diamond +problem. You can eliminete the problem by explicitely specifying the data +origin (e.g. Bar1::data) or by using virtual inheritance in Bar1 and Bar2.

+
+
+

4.5   Exercices

+
    +
  1. Write a Bar class that inherits from a Foo class and makes +constructor and destructor methods to print something when called.

    +

    solution: crash-course-4.1.cc

    +
  2. +
  3. Write a foo function and make it called from a class that has +a foo method.

    +

    solution: crash-course-4.2.cc

    +
  4. +
  5. Write a Real base class and a derived Integer class with all common +operators (+,-,*,/)

    +

    solution: crash-course-4.3.cc

    +
  6. +
  7. Write a Singleton class such that only one object of this class can be +created.

    +

    solution: crash-course-4.4.cc

    +
  8. +
  9. Write a functor class

    +

    solution: crash-course-4.5.cc

    +
  10. +
+
+
+
+

5   Exceptions

+
+

5.1   The Zen of Python

+

(by Tim Peters)

+
+
+
Beautiful is better than ugly.
+
Explicit is better than implicit.
+
Simple is better than complex.
+
Complex is better than complicated.
+
Flat is better than nested.
+
Sparse is better than dense.
+
Readability counts.
+
Special cases aren't special enough to break the rules.
+
Although practicality beats purity.
+
Errors should never pass silently.
+
Unless explicitly silenced.
+
In the face of ambiguity, refuse the temptation to guess.
+
There should be one-- and preferably only one --obvious way to do it.
+
Although that way may not be obvious at first unless you're Dutch.
+
Now is better than never.
+
Although never is often better than right now.
+
If the implementation is hard to explain, it's a bad idea.
+
If the implementation is easy to explain, it may be a good idea.
+
Namespaces are one honking great idea -- let's do more of those!
+
+
+
+
+

5.2   Catch me if you can

+

You can catch any exception using the following structure:

+
+try
+{
+    float *array = new float[-1];
+}
+catch( std::bad_alloc e )
+{
+    std::cerr << e.what() << std::endl;
+}
+
+

If the raised exception is different from the ones you're catching, program +will stop.

+
+
+

5.3   Creating your own exception

+

Creating a new exception is quite easy:

+
+#include <stdexcept>
+
+class Exception : public std::runtime_error
+{
+public:
+    Exception() : std::runtime_error("Exception") { };
+};
+
+
+
+

5.4   Standard exceptions

+

There exist some standard exceptions that can be raised in some circumstances:

+

#include <stdexcept>

+
    +
  • bad_alloc
  • +
  • bad_cast
  • +
  • bad_exception
  • +
  • bad_typeid
  • +
  • logic_error
      +
    • domain_error
    • +
    • invalid_argument
    • +
    • length_error
    • +
    • out_of_range
    • +
    +
  • +
  • runtime_error
      +
    • range_error
    • +
    • overflow_error
    • +
    • underflow_error
    • +
    +
  • +
+
+
+

5.5   Exercices

+
    +
  1. How to handle a constructor that fails ?

    +

    solution: crash-course-5.1.cc

    +
  2. +
  3. Write a program that raise 3 of the standard exceptions.

    +

    solution: crash-course-5.2.cc

    +
  4. +
  5. Write a correct division function.

    +

    solution: crash-course-5.3.cc

    +
  6. +
  7. Write a Integer (positive) class with proper exception handling +(Overflow, Underflow, DivideByZero, etc.)

    +

    solution: crash-course-5.4.cc

    +
  8. +
+
+
+
+

6   Streams

+

C++ provides input/output capability throught the iostream classes that provide +the stream concept (iXXXstream for input and oXXXstream for output).

+
+

6.1   iostream and ios

+

Screen outputs and keyboard inputs may be handled using the iostream header +file:

+
+#include <iostream>
+
+int main( int argc, char **argv )
+{
+
+    unsigned char age = 65;
+    std::cout << static_cast<unsigned>(age)     << std::endl;
+    std::cout << static_cast<void const*>(&age) << std::endl;
+
+    double f = 3.14159;
+    cout.unsetf(ios::floatfield);
+    cout.precision(5);
+    cout << f << endl;
+    cout.precision(10);
+    cout << f << endl;
+    cout.setf(ios::fixed,ios::floatfield);
+    cout << f << endl;
+
+    std::cout << "Enter a number, or -1 to quit: ";
+    int i = 0;
+    while( std::cin >> i )
+    {
+        if (i == -1) break;
+        std::cout << "You entered " << i << '\n';
+    }
+    return 0;
+}
+
+
+
+

6.2   Class input/output

+

You can implement a class input and output using friends functions:

+
+#include <iostream>
+
+class Foo {
+public:
+    friend std::ostream& operator<< ( std::ostream & output, Foo const & that )
+    { return output << that._value; }
+    friend std::istream& operator>> ( std::istream & input, Foo& foo )
+    { return input >> fred._value; }
+
+private:
+    double _value;
+};
+
+
+
+

6.3   Working with files

+
+#include <fstream>
+
+int main( int argc, char **argv )
+{
+    std::ifstream input( filename );
+    // std::ifstream input( filename, std::ios::in | std::ios::binary);
+
+    std::ofstream output( filename );
+    // std::ofstream output( filename, std::ios::out | std::ios::binary);
+
+    return 0;
+}
+
+
+
+

6.4   Working with strings

+
+#include <sstream>
+
+int main( int argc, char **argv )
+{
+    const char *svalue = "42.0";
+    int ivalue;
+    std::istringstream istream;
+    std::ostringstream ostream;
+
+    istream.str(svalue);
+    istream >> ivalue;
+    std::cout << svalue << " = " << ivalue << std::endl;
+
+    ostream.clear();
+    ostream << ivalue;
+    std::cout << ivalue << " = " << ostream.str() << std::endl;
+
+    return 0;
+}
+
+
+
+

6.5   Exercices

+
    +
  1. Write an itoa and an atoi function
  2. +
  3. Write a foo class with some attributes and write functions for writing to +file and reading from file.
  4. +
+
+
+
+

7   Templates

+

Templates are special operators that specify that a class or a function is +written for one or several generic types that are not yet known. The format for +declaring function templates is:

+
    +
  • template <typename identifier> function_declaration;
  • +
  • template <typename identifier> class_declaration;
  • +
+

You can have several templates and to actually use a class or function +template, you have to specify all unknown types:

+
+template<typename T1>
+T1 foo1( void ) { /* ... */ };
+
+template<typename T1, typename T2>
+T1 foo2( void ) { /* ... */ };
+
+template<typename T1>
+class Foo3 { /* ... */ };
+
+
+int a = foo1<int>();
+float b = foo2<int,float>();
+Foo<int> c;
+
+
+

7.1   Template parameters

+

There are three possible template types:

+
    +
  • Type

    +
    +
    +template<typename T>  T foo( void ) { /* ... */ };
    +
    +
    +
  • +
  • Non-type

    +
    +
    +template<int N>  foo( void ) { /* ... */ };
    +
    +
    +
  • +
  • Template

    +
    +
    +template< template <typename T> > foo( void ) { /* ... */ };
    +
    +
    +
  • +
+
+
+

7.2   Template function

+
+template <class T>
+T max( T a, T b)
+{
+    return( a > b ? a : b );
+}
+
+#include <sstream>
+
+int main( int argc, char **argv )
+{
+    std::cout << max<int>( 2.2, 2.5 ) << std::endl;
+    std::cout << max<float>( 2.2, 2.5 ) << std::endl;
+}
+
+
+
+

7.3   Template class

+
+template <class T>
+class Foo {
+    T _value;
+
+public:
+    Foo( T value ) : _value(value) { };
+}
+
+int main( int argc, char **argv )
+{
+    Foo<int> foo_int;
+    Foo<float> foo_float;
+}
+
+
+
+

7.4   Template specialization

+
+#include <iostream>
+
+template <class T>
+class Foo {
+    T _value;
+public:
+    Foo( T value ) : _value(value)
+    {
+        std::cout << "Generic constructor called" << std::endl;
+    };
+}
+
+template <>
+class Foo<float> {
+    float _value;
+public:
+    Foo( float value ) : _value(value)
+    {
+        std::cout << "Specialized constructor called" << std::endl;
+    };
+}
+
+int main( int argc, char **argv )
+{
+    Foo<int> foo_int;
+    Foo<float> foo_float;
+}
+
+
+
+

7.5   Exercices

+
    +
  1. Write a generic swap function
  2. +
  3. Write a generic point structure
  4. +
  5. Write templated factorial, power and exponential functions +(exp(x) = sum_n x^n/n!, exp(-x) = 1/exp(x))
  6. +
  7. Write a smart pointer class
  8. +
+
+
+
+

8   Standard Template Library

+
+

8.1   Containers

+

STL containers are template classes that implement various ways of storing +elements and accessing them.

+

Sequence containers:

+
    +
  • vector
  • +
  • deque
  • +
  • list
  • +
+

Container adaptors:

+
    +
  • stack
  • +
  • queue
  • +
  • priority_queue
  • +
+

Associative containers:

+
    +
  • set
  • +
  • multiset
  • +
  • map
  • +
  • multimap
  • +
  • bitset
  • +
+

See http://www.cplusplus.com/reference/stl/ for more information.

+
+#include <vector>
+#include <map>
+#include <string>
+
+int main( int argc, char **argv )
+{
+    std::vector<int> v;
+    v.push_back(1);
+    v.push_back(2);
+    v.push_back(3);
+
+    std::map<std::string,int> m;
+    m["one"] = 1;
+    m["two"] = 2;
+    m["three"] = 3;
+
+    return 0;
+}
+
+
+
+

8.2   Iterators

+

Iterators are a convebient tool to iterate over a container:

+
+#include <map>
+#include <string>
+#include <iostream>
+
+int main( int argc, char **argv )
+{
+    std::map<std::string,int> m;
+    m["one"] = 1;
+    m["two"] = 2;
+    m["three"] = 3;
+
+    std::map<std::string,int>::iterator iter;
+    for( iter=m.begin(); iter != m.end(); ++iter )
+    {
+        std::cout << "map[" << iter->first << "] = "
+                  << iter->second << std::endl;
+    }
+    return 0;
+}
+
+
+
+

8.3   Algorithms

+

Algorithms from the STL offer fast, robust, tested and maintained code for a lot +of standard operations on ranged elements. Don't reinvent the wheel !

+

Have a look at http://r0d.developpez.com/articles/algos-stl-fr/ (French) and +http://www.cplusplus.com/reference/algorithm/ for an overview.

+
+#include <vector>
+#include <algorithm>
+
+bool compare( const int & first, const int  & second )
+{
+    return (first < second);
+}
+
+int main( int argc, char **argv )
+{
+    std::vector<int> v(10);
+    std::sort(v.begin(), v.end(), &compare);
+
+    return 0;
+}
+
+
+
+

8.4   Exercices

+
+
    +
  1. Write a template stack class using the STL vector class
  2. +
  3. Write a generic vector class with iterators and benchmark it againt the STL +vector class
  4. +
+
+
+
+ +
+ + diff --git a/README.rst b/README.rst new file mode 100644 index 0000000..a66369e --- /dev/null +++ b/README.rst @@ -0,0 +1,1098 @@ +.. sectnum:: + +=============================================================================== +C++ crash course for C programmers +=============================================================================== +:Author: `Nicolas P. Rougier `_ +:Sources: `crash-course.rst `_ + +.. contents:: + :local: + :depth: 2 + +Foreword +=============================================================================== +This is an introduction to C++ for C programmers: + +* If you can't understand the code below, you'd better start with a C tutorial. + + .. code:: c++ + + #include + + void main (int argc, char **argv) + { + printf("Hello World!\n"); + } + +* If you don't know what are the stack and the heap, you'd better have a look at + some architecture & system introduction. +* If you know java, that might help a bit. +* If you think `python `_ is cool, you're right, but + still, this is not the place. +* If you never heard about `Bjarne Stroustrup + `_, you might be at the right place. + +* Here is a list of C++ specific keywords:: + + asm dynamic_cast namespace reinterpret_cast try + bool explicit new static_cast typeid + catch false operator template typename + class friend private this using + const_cast inline public throw virtual + delete mutable protected true wchar_t + + + + +From C to C++ +=============================================================================== + +Even if C++ is slanted toward object-oriented programming (OOP), you can +nevertheless use any c++ compiler to compile c code and benefits from some c++ +goodies. + + +Input/Output +------------ + +Prefer the use of ```` for input/output operations (see stream +section for explanation). + +.. code:: c++ + + #include + + int main (int argc, char **argv) + { + int i; + std::cout << "Please enter an integer value: "; + std::cin >> i; + std::cout << "The value you entered is " << i << std::endl; + return 0; + } + + +New/Delete +---------- + +The ``new`` and ``delete`` keywords are used to allocate and free memory. They +are "object-aware" so you'd better use them instead of ``malloc`` and +``free``. In any case, never cross the streams (new/free or malloc/delete). + +.. code:: c++ + + int *a = new int; + delete a; + + int *b = new int[5]; + delete [] b; + +``delete`` does two things: it calls the destructor and it deallocates the +memory. + +References +---------- + +A reference allows to declare an alias to another variable. As long as the +aliased variable lives, you can use indifferently the variable or the alias. + +.. code:: c++ + + int x; + int& foo = x; + + foo = 42; + std::cout << x << std::endl; + +References are extremely useful when used with function arguments since it +saves the cost of copying parameters into the stack when calling the function. + +Default parameters +------------------ + +You can specify default values for function parameters. When the function is +called with fewer parameters, default values are used. + +.. code:: c++ + + float foo( float a=0, float b=1, float c=2 ) + {return a+b+c;} + + cout << foo(1) << endl + << foo(1,2) << endl + << foo(1,2,3) << endl; + +You should obtain values 4, 5 and 6. + + +Namespaces +---------- + +Namespace allows to group classes, functions and variable under a common scope +name that can be referenced elsewhere. + +.. code:: c++ + + namespace first { int var = 5; } + namespace second { int var = 3; } + cout << first::var << endl << second::var << endl; + +You should obtain values 3 and 5. There exists some standard namespace in the +standard template library such as std. + + +Overloading +----------- + +Function overloading refers to the possibility of creating multiple functions +with the same name as long as they have different parameters (type and/or +number). + +.. code:: c++ + + float add( float a, float b ) + {return a+b;} + + int add( int a, int b ) + {return a+b;} + +It is not legal to overload a function based on the return type (but you can do it +`anyway +`_) + +Const & inline +-------------- + +Defines and macros are bad if not used properly as illustrated below + +.. code:: c++ + + #define SQUARE(x) x*x + + int result = SQUARE(3+3); + +For constants, prefer the const notation: + +.. code:: c++ + + const int two = 2; + +For macros, prefer the inline notation: + +.. code:: c++ + + int inline square(int x) + { + return x*x; + } + +Mixing C and C++ +---------------- + +.. code:: c++ + + #ifdef __cplusplus + extern "C" { + #endif + + #include "some-c-code.h" + + #ifdef __cplusplus + } + #endif + + + +Exercises +--------- + +1. Write a basic makefile for compiling sources + + **solution**: `Makefile `_ + +2. How would you declare: + + * A pointer to a char + * A constant pointer to a char + * A pointer to a constant char + * A constant pointer to a constant char + * A reference to a char + * A reference to a constant char + + **solution**: `crash-course-2.1.cc `_ + +3. Create a two-dimensional array of integers (size is n x n), fill it with + corresponding indices (a[i][j] = i*n+j), test it and finally, delete it. + + **solution**: `crash-course-2.2.cc `_ + +4. Write a function that swap two integers, then two pointers. + + **solution**: `crash-course-2.3.cc `_ + +5. Is this legal ? + + .. code:: c++ + + int add( int a, int b ) { return a+b; } + + int add( int a, int b, int c=0 ) { return a+b+c; } + + **solution**: `crash-course-2.4.cc `_ + +6. Write a ``const correct`` division function. + + **solution**: `crash-course-2.5.cc `_ + +7. What's the difference between ``int const* p``, ``int* const p`` + and ``int const* const p`` ? + + **solution**: `crash-course-2.6.cc `_ + + + +Classes +=============================================================================== + +A class migh be considered as an extended concept of a data structure: instead +of holding only data, it can hold both data and functions. An object is an +instantiation of a class. By default, all attributes and functions of a class +are private (see below Access control). If you want a public default behavior, +you can use keyword ``struct`` instead of keyword ``class`` in the declaration. + +.. code:: c++ + + class Foo { + int attribute; + int function( void ) { }; + }; + + struct Bar { + int attribute; + int function( void ) { }; + }; + + Foo foo; + foo.attribute = 1; // WRONG + + Bar bar; + bar.attribute = 1; // OK + + +Constructors +------------ + +It is possible to specify zero, one or more constructors for the class. + +.. code:: c++ + + #include + + class Foo { + public: + Foo( void ) + { std::cout << "Foo constructor 1 called" << std::endl; } + Foo( int value ) + { std::cout << "Foo constructor 2 called" << std::endl; } + }; + + int main( int argc, char **argv ) + { + Foo foo_1, foo_2(2); + return 0; + } + + +Destructor +---------- + +There can be only one destructor per class. It takes no argument and returns +nothing. + +.. code:: c++ + + #include + + class Foo { + public: + ~Foo( void ) + { std::cout << "Foo destructor called" << std::endl; } + } + int main( int argc, char **argv ) + { + Foo foo(); + return 0; + } + +Note that you generally never need to explicitly call a destructor. + + +Access control +-------------- + +You can have fine control over who is granted access to a class function or +attribute by specifying an explicit access policy: + +* **public**: Anyone is granted access +* **protected**: Only derived classes are granted access +* **private**: No one but friends are granted access + + +Initialization list +------------------- + +Object's member should be initialized using initialization lists + +.. code:: c++ + + class Foo + { + int _value; + public: + Foo(int value=0) : _value(value) { }; + }; + +It's cheaper, better and faster. + + +Operator overloading +-------------------- + +.. code:: c++ + + class Foo { + private: + int _value; + + public: + Foo( int value ) : _value(value) { }; + + Foo operator+ ( const Foo & other ) + { + return Foo( _value+ other._value ); + } + + Foo operator* ( const Foo & other ); + { + return Foo( _value * other._value ); + } + } + + +Friends +------- + +Friends are either functions or other classes that are granted privileged +access to a class. + +.. code:: c++ + + #include + + class Foo { + public: + friend std::ostream& operator<< ( std::ostream& output, + Foo const & that ) + { + return output << that._value; + } + private: + double _value; + }; + + int main( int argc, char **argv ) + { + Foo foo; + std::cout << "Foo object: " << foo << std::endl; + return 0 + } + +Exercices +--------- + +1. Why the following code doesn't compile ? + + .. code:: c++ + + class Foo { Foo () { }; }; + + int main( int argc, char **argv ) + { + Foo foo; + } + + **solution**: `crash-course-3.1.cc `_ + +2. Write a ``Foo`` class with default and copy constructors and add also an + assignment operator. Write some code to highlight the use of each of them. + + **solution**: `crash-course-3.2.cc `_ + +3. Write a ``Point`` class that can be constructed using cartesian or polar + coordinates. + + **solution**: `crash-course-3.3.cc `_ + +4. Write a ``Foo`` class and provide it with an input method. + + **solution**: `crash-course-3.4.cc `_ + +5. Is is possible to write something like ``foo.method1().method2()`` ? + + **solution**: `crash-course-3.5.cc `_ + + +Inheritance +=============================================================================== + +Basics +------ + +Inheritance is done at the class definition level by specifying the base class +and the type of inheritance. + +.. code:: c++ + + class Foo { /* ... */ }; + class Bar_public : public Foo { /* ... */ }; + class Bar_private : private Foo { /* ... */ }; + class Bar_protected : protected Foo { /* ... */ }; + +``Bar_public``, ``Bar_private`` and ``Bar_protected`` are derived from ``Foo``. +``Foo`` is the base class of ``Bar_public``, ``Bar_private`` and ``Bar_protected``. + +* In ``Bar_public``, public parts of ``Foo`` are public, + protected parts of ``Foo`` are protected +* In ``Bar_private``, public and protected parts of ``Foo`` are private +* In ``Bar_protected``, public and protected parts of ``Foo`` are protected + + +Virtual methods +--------------- + +A ``virtual`` function allows derived classes to replace the implementation +provided by the base class (yes, it is not automatic...). Non virtual methods +are resolved statically (at compile time) while virtual methods are resolved +dynamically (at run time). + +.. code:: c++ + + class Foo { + public: + Foo( void ); + void method1( void ); + virtual void method2( void ); + }; + + class Bar : public Foo { + public: + Bar( void ); + void method1( void ); + void method2( void ); + }; + + Foo *bar = new Bar(); + bar->method1(); + bar->method2(); + +Make sure your destructor is virtual when you have derived class. + + +Abstract classes +---------------- + +You can define pure virtual method that prohibits the base object to be +instantiated. Derived classes need then to implement the virtual method. + +.. code:: c++ + + class Foo { + public: + Foo( void ); + virtual void method( void ) = 0; + }; + + class Bar: public Foo { + public: + Foo( void ); + void method( void ) { }; + }; + + + +Multiple inheritance +-------------------- + +A class may inherit from multiple base classes but you have to be careful: + +.. code:: c++ + + class Foo { protected: int data; }; + class Bar1 : public Foo { /* ... */ }; + class Bar2 : public Foo { /* ... */ }; + class Bar3 : public Bar1, public Bar2 { + void method( void ) + { + data = 1; // !!! BAD + } + }; + +In class Bar3, the ``data`` reference is ambiguous since it could refer to +Bar1::data or Bar2::data. This problem is referred as the **diamond +problem**. You can eliminete the problem by explicitely specifying the data +origin (e.g. Bar1::data) or by using virtual inheritance in Bar1 and Bar2. + + +Exercices +--------- + +1. Write a ``Bar`` class that inherits from a ``Foo`` class and makes + constructor and destructor methods to print something when called. + + **solution**: `crash-course-4.1.cc `_ + +2. Write a ``foo`` function and make it called from a class that has + a ``foo`` method. + + **solution**: `crash-course-4.2.cc `_ + +3. Write a ``Real`` base class and a derived ``Integer`` class with all common + operators (+,-,*,/) + + **solution**: `crash-course-4.3.cc `_ + +4. Write a ``Singleton`` class such that only one object of this class can be + created. + + **solution**: `crash-course-4.4.cc `_ + +5. Write a functor class + + **solution**: `crash-course-4.5.cc `_ + + + + + +Exceptions +=============================================================================== + +The Zen of Python +----------------- +(by Tim Peters) + + | Beautiful is better than ugly. + | Explicit is better than implicit. + | Simple is better than complex. + | Complex is better than complicated. + | Flat is better than nested. + | Sparse is better than dense. + | Readability counts. + | Special cases aren't special enough to break the rules. + | Although practicality beats purity. + | **Errors should never pass silently.** + | **Unless explicitly silenced.** + | In the face of ambiguity, refuse the temptation to guess. + | There should be one-- and preferably only one --obvious way to do it. + | Although that way may not be obvious at first unless you're Dutch. + | Now is better than never. + | Although never is often better than *right* now. + | If the implementation is hard to explain, it's a bad idea. + | If the implementation is easy to explain, it may be a good idea. + | Namespaces are one honking great idea -- let's do more of those! + + +Catch me if you can +------------------- + +You can catch any exception using the following structure: + +.. code:: c++ + + try + { + float *array = new float[-1]; + } + catch( std::bad_alloc e ) + { + std::cerr << e.what() << std::endl; + } + +If the raised exception is different from the ones you're catching, program +will stop. + + +Creating your own exception +--------------------------- + +Creating a new exception is quite easy: + +.. code:: c++ + + #include + + class Exception : public std::runtime_error + { + public: + Exception() : std::runtime_error("Exception") { }; + }; + + +Standard exceptions +------------------- + +There exist some standard exceptions that can be raised in some circumstances: + +``#include `` + +* bad_alloc +* bad_cast +* bad_exception +* bad_typeid +* logic_error + + * domain_error + * invalid_argument + * length_error + * out_of_range + +* runtime_error + + * range_error + * overflow_error + * underflow_error + + + +Exercices +--------- + +1. How to handle a constructor that fails ? + + **solution**: `crash-course-5.1.cc `_ + +2. Write a program that raise 3 of the standard exceptions. + + **solution**: `crash-course-5.2.cc `_ + +3. Write a correct division function. + + **solution**: `crash-course-5.3.cc `_ + +4. Write a ``Integer`` (positive) class with proper exception handling + (``Overflow``, ``Underflow``, ``DivideByZero``, etc.) + + **solution**: `crash-course-5.4.cc `_ + + + +Streams +=============================================================================== + +C++ provides input/output capability throught the iostream classes that provide +the stream concept (iXXXstream for input and oXXXstream for output). + +iostream and ios +---------------- + +Screen outputs and keyboard inputs may be handled using the iostream header +file: + +.. code:: c++ + + #include + + int main( int argc, char **argv ) + { + + unsigned char age = 65; + std::cout << static_cast(age) << std::endl; + std::cout << static_cast(&age) << std::endl; + + double f = 3.14159; + cout.unsetf(ios::floatfield); + cout.precision(5); + cout << f << endl; + cout.precision(10); + cout << f << endl; + cout.setf(ios::fixed,ios::floatfield); + cout << f << endl; + + std::cout << "Enter a number, or -1 to quit: "; + int i = 0; + while( std::cin >> i ) + { + if (i == -1) break; + std::cout << "You entered " << i << '\n'; + } + return 0; + } + + +Class input/output +------------------ + +You can implement a class input and output using friends functions: + +.. code:: c++ + + #include + + class Foo { + public: + friend std::ostream& operator<< ( std::ostream & output, Foo const & that ) + { return output << that._value; } + friend std::istream& operator>> ( std::istream & input, Foo& foo ) + { return input >> fred._value; } + + private: + double _value; + }; + +Working with files +------------------ + +.. code:: c++ + + #include + + int main( int argc, char **argv ) + { + std::ifstream input( filename ); + // std::ifstream input( filename, std::ios::in | std::ios::binary); + + std::ofstream output( filename ); + // std::ofstream output( filename, std::ios::out | std::ios::binary); + + return 0; + } + + + +Working with strings +-------------------- + +.. code:: c++ + + #include + + int main( int argc, char **argv ) + { + const char *svalue = "42.0"; + int ivalue; + std::istringstream istream; + std::ostringstream ostream; + + istream.str(svalue); + istream >> ivalue; + std::cout << svalue << " = " << ivalue << std::endl; + + ostream.clear(); + ostream << ivalue; + std::cout << ivalue << " = " << ostream.str() << std::endl; + + return 0; + } + + +Exercices +--------- + +1. Write an ``itoa`` and an ``atoi`` function +2. Write a foo class with some attributes and write functions for writing to + file and reading from file. + + + +Templates +=============================================================================== + +Templates are special operators that specify that a class or a function is +written for one or several generic types that are not yet known. The format for +declaring function templates is: + +* template function_declaration; +* template class_declaration; + +You can have several templates and to actually use a class or function +template, you have to specify all unknown types: + +.. code:: c++ + + template + T1 foo1( void ) { /* ... */ }; + + template + T1 foo2( void ) { /* ... */ }; + + template + class Foo3 { /* ... */ }; + + + int a = foo1(); + float b = foo2(); + Foo c; + +Template parameters +------------------- + +There are three possible template types: + +* **Type** + + .. code:: c++ + + template T foo( void ) { /* ... */ }; + + +* **Non-type** + + .. code:: c++ + + template foo( void ) { /* ... */ }; + + +* **Template** + + .. code:: c++ + + template< template > foo( void ) { /* ... */ }; + + +Template function +----------------- + +.. code:: c++ + + template + T max( T a, T b) + { + return( a > b ? a : b ); + } + + #include + + int main( int argc, char **argv ) + { + std::cout << max( 2.2, 2.5 ) << std::endl; + std::cout << max( 2.2, 2.5 ) << std::endl; + } + + + +Template class +-------------- + +.. code:: c++ + + template + class Foo { + T _value; + + public: + Foo( T value ) : _value(value) { }; + } + + int main( int argc, char **argv ) + { + Foo foo_int; + Foo foo_float; + } + + +Template specialization +----------------------- + +.. code:: c++ + + #include + + template + class Foo { + T _value; + public: + Foo( T value ) : _value(value) + { + std::cout << "Generic constructor called" << std::endl; + }; + } + + template <> + class Foo { + float _value; + public: + Foo( float value ) : _value(value) + { + std::cout << "Specialized constructor called" << std::endl; + }; + } + + int main( int argc, char **argv ) + { + Foo foo_int; + Foo foo_float; + } + + +Exercices +--------- + +1. Write a generic swap function +2. Write a generic point structure +3. Write templated factorial, power and exponential functions + (exp(x) = sum_n x^n/n!, exp(-x) = 1/exp(x)) +4. Write a smart pointer class + + + + + +Standard Template Library +=============================================================================== + +Containers +---------- + +STL containers are template classes that implement various ways of storing +elements and accessing them. + +**Sequence containers**: + +* vector +* deque +* list + +**Container adaptors**: + +* stack +* queue +* priority_queue + +**Associative containers**: + +* set +* multiset +* map +* multimap +* bitset + +See http://www.cplusplus.com/reference/stl/ for more information. + + +.. code:: c++ + + #include + #include + #include + + int main( int argc, char **argv ) + { + std::vector v; + v.push_back(1); + v.push_back(2); + v.push_back(3); + + std::map m; + m["one"] = 1; + m["two"] = 2; + m["three"] = 3; + + return 0; + } + + +Iterators +--------- + +Iterators are a convebient tool to iterate over a container: + +.. code:: c++ + + #include + #include + #include + + int main( int argc, char **argv ) + { + std::map m; + m["one"] = 1; + m["two"] = 2; + m["three"] = 3; + + std::map::iterator iter; + for( iter=m.begin(); iter != m.end(); ++iter ) + { + std::cout << "map[" << iter->first << "] = " + << iter->second << std::endl; + } + return 0; + } + + + +Algorithms +---------- + +Algorithms from the STL offer fast, robust, tested and maintained code for a lot +of standard operations on ranged elements. Don't reinvent the wheel ! + +Have a look at http://r0d.developpez.com/articles/algos-stl-fr/ (French) and +http://www.cplusplus.com/reference/algorithm/ for an overview. + +.. code:: c++ + + #include + #include + + bool compare( const int & first, const int & second ) + { + return (first < second); + } + + int main( int argc, char **argv ) + { + std::vector v(10); + std::sort(v.begin(), v.end(), &compare); + + return 0; + } + + +Exercices +--------- + 1. Write a template stack class using the STL vector class + 2. Write a generic vector class with iterators and benchmark it againt the STL + vector class + + + +External links +=============================================================================== + +* | C++ FAQ — Frequently Asked Questions + | http://www.parashift.com/c++-faq-lite/ + +* | Boost free peer-reviewed portable C++ source libraries + | http://www.boost.org/ + +* | Bjarne Stroustrup homepage + | http://www2.research.att.com/~bs/ + +* | Complete reference on C++ Standard Library + | http://en.cppreference.com/w/cpp + +* | C++11 main features + | http://en.wikipedia.org/wiki/C%2B%2B11 + +* | The definitive C++ book guide + | http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list + +* | comp.lang.c++ + | http://groups.google.com/group/comp.lang.c++/topics + +* | GNU make + | http://www.gnu.org/s/make/manual/make.html + +* | Les meilleurs cours et tutoriaux (in **French** as you may have already guessed...) + | http://cpp.developpez.com/cours/ diff --git a/exam.html b/exam.html new file mode 100644 index 0000000..3caac39 --- /dev/null +++ b/exam.html @@ -0,0 +1,225 @@ + + + + + + +C++ exam + + + +
+

C++ exam

+ +

Name:

+

Surname:

+
+

1   Extern

+

The code below declares and defines variable x. True or False ?

+
+extern int x;
+
+
+
+

2   Namespace

+

In namespace foo, the function bar can access the variable x also declared in +namespace foo ? True or False ?

+
+#include <iostream>
+
+namespace foo
+{
+    void bar()
+    {
+        x++;
+    }
+    int x;
+}
+
+int main(int argc, char** argv)
+{
+    return 0;
+}
+
+
+
+

3   References

+

What is the output of the following program ?

+
+#include <iostream>
+using namespace std;
+
+void swap1( int  a, int  b ) { int c=a; a=b; b=c; }
+void swap2( int *a, int *b ) { int c=*a; *a=*b; *b=c; }
+void swap3( int &a, int &b ) { int &c=a; a=b; b=c; }
+
+int main( int argc, char **argv )
+{
+    int a, b;
+
+    a = 1; b = 2; swap1(a,b);
+    cout << "a: " << a << ", " <<"b: " << b << endl;
+
+    a = 1; b = 2; swap2(&a,&b);
+    cout << "a: " << a << ", " <<"b: " << b << endl;
+
+    a = 1; b = 2; swap3(a,b);
+    cout << "a: " << a << ", " <<"b: " << b << endl;
+}
+
+
+
+

4   Inheritance

+

What is the output of the program ?

+
+#include <iostream>
+
+struct A { unsigned int color; };
+struct B : public A { };
+struct C : public A { };
+struct D : public B, public C { };
+
+int main(int argc, char** argv)
+{
+   D d;
+   d.color = 3;
+   std::cout << d.color << std::endl;
+   return 0;
+}
+
+
+
+

5   Inheritance

+

How many times is "Hello World" printed by this program ?

+
+#include <iostream>
+
+struct A { A() {  std::cout << "Hello World" << std::endl; } };
+struct A1 : public A { };
+struct A2 : public A { };
+struct A3 : public A { };
+struct A4 : public A { };
+struct B : public A1, public A2, public A3, public A4 { };
+
+int main(int argc, char** argv)
+{
+    B b;
+    return 0;
+}
+
+
+
+

6   Initialization

+

What is the value of x, y & z ?

+
+#include <iostream>
+
+struct A
+{
+  A(int n) : x(n++), y(n++), z(n++) {}
+  int x;
+  int y;
+  int z;
+};
+
+int main(int argc, char** argv)
+{
+  Foo f(3);
+
+  std::cout << "x: " << f.x << std::endl;
+  std::cout << "y: " << f.y << std::endl;
+  std::cout << "z: " << f.z << std::endl;
+
+  return 0;
+}
+
+
+
+

7   Logic

+

What value gets printed by the program?

+
+#include <iostream>
+
+int main(int argc, char** argv)
+{
+  int x = 0;
+  int y = 0;
+
+  if (x++ && y++)
+  {
+    y += 2;
+  }
+
+  std::cout << x + y << std::endl;
+
+  return 0;
+}
+
+
+
+

8   Constructors

+

Which lines below should not compile ?

+
+struct A
+{
+   A(int x) : n(x) {}
+   int n;
+};
+
+int main(int argc, char** argv)
+{
+  A a1;
+  A a2(2);
+  A a3(a2);
+  return 0;
+}
+
+
+
+

9   Memory

+

Which of the following implementations of the reset function is best for +initializing the array to all zero.

+
+class foo{
+public:
+    foo(){
+        reset();
+    }
+private:
+    void reset(){
+
+    // A // memset(x, 0, 50);
+    // B // memset(x, 0, sizeof(x));
+    // C // memset(x, 0, 50 * 4);
+    // D // memset(x, 0, 50 * sizeof(x));
+    }
+
+    long x[50];
+};
+
+
+
+

10   References

+

What is the output of the program ?

+
+#include <iostream>
+
+int main(int argc, char** argv)
+{
+  // assume address of x is 0x822222222
+  int x = 3;
+
+  int*& rpx = &x;
+
+  std::cout << rpx << std::endl;
+
+  return 0;
+}
+
+
+
+

11   End

+
+
+ + diff --git a/exam.rst b/exam.rst new file mode 100644 index 0000000..18ead72 --- /dev/null +++ b/exam.rst @@ -0,0 +1,240 @@ +.. sectnum:: + +=============================================================================== +C++ exam +=============================================================================== + +Name: + + +.. :Author: `Nicolas P. Rougier `_ +.. :Sources: `exam.rst `_ +.. Most questions comes from http://www.mycppquiz.com/ + + +Extern +=============================================================================== + +The code below declares and defines variable x. **True** or **False** ? + +.. code:: c++ + + extern int x; + + +Namespace +=============================================================================== +In namespace foo, the function bar can access the variable x also declared in +namespace foo ? **True** or **False** ? + +.. code:: c++ + + #include + + namespace foo + { + void bar() + { + x++; + } + int x; + } + + int main(int argc, char** argv) + { + return 0; + } + + +References +=============================================================================== +What is the output of the following program ? + +.. code:: c++ + + #include + using namespace std; + + void swap1( int a, int b ) { int c=a; a=b; b=c; } + void swap2( int *a, int *b ) { int c=*a; *a=*b; *b=c; } + void swap3( int &a, int &b ) { int &c=a; a=b; b=c; } + + int main( int argc, char **argv ) + { + int a, b; + + a = 1; b = 2; swap1(a,b); + cout << "a: " << a << ", " <<"b: " << b << endl; + + a = 1; b = 2; swap2(&a,&b); + cout << "a: " << a << ", " <<"b: " << b << endl; + + a = 1; b = 2; swap3(a,b); + cout << "a: " << a << ", " <<"b: " << b << endl; + } + + +Inheritance +=============================================================================== +What is the output of the program ? + +.. code:: c++ + + #include + + struct A { unsigned int color; }; + struct B : public A { }; + struct C : public A { }; + struct D : public B, public C { }; + + int main(int argc, char** argv) + { + D d; + d.color = 3; + std::cout << d.color << std::endl; + return 0; + } + +Inheritance +=============================================================================== +How many times is "Hello World" printed by this program ? + +.. code:: c++ + + #include + + struct A { A() { std::cout << "Hello World" << std::endl; } }; + struct A1 : public A { }; + struct A2 : public A { }; + struct A3 : public A { }; + struct A4 : public A { }; + struct B : public A1, public A2, public A3, public A4 { }; + + int main(int argc, char** argv) + { + B b; + return 0; + } + + +Initialization +=============================================================================== +What is the value of x, y & z ? + +.. code:: c++ + + #include + + struct A + { + A(int n) : x(n++), y(n++), z(n++) {} + int x; + int y; + int z; + }; + + int main(int argc, char** argv) + { + Foo f(3); + + std::cout << "x: " << f.x << std::endl; + std::cout << "y: " << f.y << std::endl; + std::cout << "z: " << f.z << std::endl; + + return 0; + } + + +Logic +=============================================================================== +What value gets printed by the program? + +.. code:: c++ + + #include + + int main(int argc, char** argv) + { + int x = 0; + int y = 0; + + if (x++ && y++) + { + y += 2; + } + + std::cout << x + y << std::endl; + + return 0; + } + +Constructors +=============================================================================== +Which lines below should not compile ? + +.. code:: c++ + + struct A + { + A(int x) : n(x) {} + int n; + }; + + int main(int argc, char** argv) + { + A a1; + A a2(2); + A a3(a2); + return 0; + } + + + +Memory +=============================================================================== +Which of the following implementations of the reset function is best for +initializing the array to all zero. + +.. code:: c++ + + class foo{ + public: + foo(){ + reset(); + } + private: + void reset(){ + + // A // memset(x, 0, 50); + // B // memset(x, 0, sizeof(x)); + // C // memset(x, 0, 50 * 4); + // D // memset(x, 0, 50 * sizeof(x)); + } + + long x[50]; + }; + + +References +=============================================================================== +What is the output of the program ? + +.. code:: c++ + + #include + + int main(int argc, char** argv) + { + // assume address of x is 0x822222222 + int x = 3; + + int*& rpx = &x; + + std::cout << rpx << std::endl; + + return 0; + } + + +End +=============================================================================== diff --git a/exam/Makefile b/exam/Makefile new file mode 100644 index 0000000..4856287 --- /dev/null +++ b/exam/Makefile @@ -0,0 +1,35 @@ +# Copyright (C) 2012 Nicolas P. Rougier +# +# This program is free software: you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation, either version 3 of the License, or (at your option) any later +# version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT +# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS +# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. + +# You should have received a copy of the GNU General Public License along with +# this program. If not, see . +PLATFORM = $(shell uname) +CXX = g++ +CXXFLAGS = -Wall -ansi -pedantic + +SOURCES:= $(wildcard *.cc) +TARGETS := $(SOURCES:.cc=) + +all: $(TARGETS) + + +define template +$(1): $(1).cc + @echo "Building $$@... " + @$(CXX) $(1).cc $(CXXFLAGS) -o $$@ +endef +$(foreach target,$(TARGETS),$(eval $(call template,$(target)))) + +clean: + @-rm -f $(TARGETS) + +distclean: clean + @-rm -f *~ diff --git a/exam/exam-1 b/exam/exam-1 new file mode 100755 index 0000000000000000000000000000000000000000..216b454b93378b04f532070eb62507d08b9907f4 GIT binary patch literal 8648 zcmeHMO=w(I6h1FAno(mqEiM#|Jgd=QCFw#+x{;ZXp|7;WX`4V0!tKmtl1!PO@Mb1W z)IuRB4xunR5yYRJ;HFELMi;Fsb=U5KC`7DKq__yu^!whsH+eG?>r#b#;J$Ouz2|=K zyzk6B?z`vvo!{^Gi#Rcnt9>Feh?aO%*SI;Q@#@r{`(Mbw5yXxf(Tn#xwIFo?0rFmy14}y74A8-g6p&HhJHZp7@&8%cbhPDpeP1 zaO%dpsPVEIfcC>gsp67a@N<=7=+%vPUE?w56x#T0{H-vr9|U=wOi!mHZpdFpUQK=@ zc_psNjZ({gZ4q&)m7I@sD0ML2h`9xD%vv)P)k;;%s=ijq*UD1OKv^_tigz!RH=F<1>c*y^dc0J{RDl z-k2{OJ2rY^6ugx3n1=MMb3VnW)3NTtTD?)Mj7~(?y$mn%_Jtef3|%Xh0n318z%pPN zunbrR{uc~f60h}(xBl~8Z{teByVgv$cGkafHh+qF&L3Xu$KT@K`ewpgKPk;W+1uuR zsdZ!fMW}mi$PAXZuKeY-ns;wxw)w~#neA5Q&PL|W+_&xB;d>b2eph}CcV%a<4c&&7 zzOXy|9dw)fUh}ON)%51xkGnWFepgc1=Xb&Yc6m>QJ3S`_8$u|Ih2p$@UYymWlN{(z z@FuTenE2VUh#JOxR`F>xVuuq!rR5MLY5A(g@Vbe!DtM#nb^oxr5j*X7lzGc8N zU>UFsSOzQumI2FvWxz6E8L$jk1}p>rO$H7hm6?fiB1cjzrUk`tl}Ei9#p`qaNL&2z zBPmr}Ej6SaK0u$6fqEn7H{^`OmAq2Pm8z1RnoawQGE=OslzbF57p1SVgk{A-vr$Ab zJV(4!L5a7@(sP-|A2Hb)!sWB)QPC>M+=}F5^0kYRo4owM%PrTiwl$Orx?DKOLkxW` z@ff;?a53i>hqZ0aF<2MnygA1hh8=UT7{YUolW3eb=N%KYG2uq);IvJhZYo^IFanvz w71Mh*>zj-Tl49Q#wH#EmRX|ZeLcM~5?>-$$^|GZ5mnvX5q&&<-Po{962X$i_ga7~l literal 0 HcmV?d00001 diff --git a/exam/exam-1.cc b/exam/exam-1.cc new file mode 100644 index 0000000..dd5dcd4 --- /dev/null +++ b/exam/exam-1.cc @@ -0,0 +1,7 @@ + +extern int x; + +int main(int argc, char** argv) +{ + return 0; +} diff --git a/exam/exam-10 b/exam/exam-10 new file mode 100755 index 0000000000000000000000000000000000000000..07360f87335458d7a6a23ea38ab18dcce9a4d4b1 GIT binary patch literal 9016 zcmeHNU1(fI6h51zCTiMjYX#e?-4>(4YMV-x^+B7|EWM$zjZFfj5+=KwP4|}liMw}W zS{hhb6qXRkLqP?93L;eS$p>l0m$pJ*#GePD;7gGT5i7~7NZu|C`b zbI+WabG|uqX729noc-?R@3)&p0*xZY1`%0@a`rxvwf zOMzN(MTt09ps3Vf>MOx-x zA@io48C7;>EDNQ2yl*sKzXqVZ8Yz`Xs&c$}}9D^-+AXSt}hqs9uE_%i>FXuKAU zN4XmBe%)@EQnCEfE?yqL5sjx`3)id~uezO`O2xD3bT+euU%S3ZjTbTs;H%*+eU9|? z9y}1~={27L0I1m~8ZfNE7`JNQwu=-y(I(JiY+At0y9rT3kVn9a;FI8dx7_}1BI{8P z1Au@Jg7u@2%;yWoYSl8^SE3;7A6TJ-uU!a*_PYxC+^&=z+ckP3H42%u1%-aBoqwbA z#*cg7|0Hz$-G84eSDru{LMhVhq0*OgDBOEbqugsUpQm^8gYyofaE^?*$R3pDrC1;y zd1o}fW5>=Hb|Nlz%vEyZRbvXRPT$sNcxyD1$<;WaoHyxQPN3Kstt`A=tYunl*;ytNvm97V^ z^3;Mgvt|n4#TM}1frVB2IyiiZpjAZub2tyl`AUT&m%p9k(Q^1w+twnu7(Dn;E-Xw( zZj}}Sg}u{}g_o#bcphVH(qlXeb%-Y`m5Ozqwj^uj;rIST!^{S_VFCRiHhP{^+P}ca zm3EF_Y5&rFeuZa}hQB_JM{+A`8(DjqHJ*`@hgn0BzM03;Q12e7v=4*NqR6A{09A9I zM|h6miG+o};Yh4AqOCZwZ1heofiB1(Lb=4TNr97xB`_Hb1Y4V1IM6d_;}|2iFPQ7X}zhgf{EUAB1^UpQsMFQJ>@+06!z>k0*0Y3tM1pEm25%446N5GGO z9|1oCegy7)1lDhtp?yOl8@iaRa+BdIhI})U*RSO|W+fM1-=);ig9A?3&gNAtnosQM zMb`3_-H{1Fch}0@J-XZ40BaSWjH)Q|_O?TlezfU2=HH;CHSa`ojvSCCB~PWJc1HRS z9_h{zdX)a{S4_> zqs)cSGS3GRMU7J2W+Hxdb600)$jeo&!$rmS`hNq=3sN@s7rf)49Mbn0uTtivj=mQe zq>O8+5iO5GZUcz9Pf2On+^aZRHuow;$c+IQgE;JI6xy5nmk%hTK}cJq%AQOAzEIc__evQI+FW>ggaWf)E5om?UA%AK|?YTQlw!*0Oo3oB)3 vnHU%4?gHe-T|U7P7grql^JN=CneF1a;q9tBZr+tT+-+OCVZE)o?B)0mPYU(W literal 0 HcmV?d00001 diff --git a/exam/exam-10.cc b/exam/exam-10.cc new file mode 100644 index 0000000..442126a --- /dev/null +++ b/exam/exam-10.cc @@ -0,0 +1,12 @@ +#include + +int main(int argc, char** argv) +{ + // assume address of x is 0x822222222 + int x = 3; + +// int*& rpx = &x; +// std::cout << rpx << std::endl; + + return 0; +} diff --git a/exam/exam-2 b/exam/exam-2 new file mode 100755 index 0000000000000000000000000000000000000000..31acdf275338b643be02a2e3fdee235ffe11d585 GIT binary patch literal 9120 zcmeHNPi$0082?^d?5c$>1rsbH3$dmVEhQkS2cbnayvC+fN)4%Lrn}oM`^f%jcHfpl zXtH7b!=^T=UgV(Bg9i_qaD*dbLOiH=^We!SS+ykfPe?X<8^6&+T?vnR`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;f(BQ$cwT|8Q7nMNJMjadi=yo|N+_Dh5!rz{esVxgB_1;MvKg)^2~G zGvJ&eZNLG?C;B{t_lC6H^NlubFX;N$Y4easpPP)(#xd8ZwiB?M0pgywWVP*{yG(2Q zg7z=aMtc()|DvvU&t*P^U2nh{0ypRGkofNT%~g~!KBwcaYr9k1-<0DR>c~wzVJz7= z6r@2`9a&$lT(URS*gT4BMq-aPBDEkvx@*e=xM5ayWL$M3bENO+p`Jdadb!d#rF!OI z?%TtERD^6R;#`(np}2JxRw}7N_*2AKG-Ic;5y$SdEKw8AzXuREX!ms~Wu zxMX+qBw8#t!-e7ImzrE&Ot_<8vF4P!B$cyJ%PW@{tG*zsRXDFk^-EEH9ag-6B<^1i CT^8d2 literal 0 HcmV?d00001 diff --git a/exam/exam-2.cc b/exam/exam-2.cc new file mode 100644 index 0000000..733a507 --- /dev/null +++ b/exam/exam-2.cc @@ -0,0 +1,15 @@ +#include + +namespace foo +{ + void bar() + { +// x++; + } + int x; +} + +int main(int argc, char** argv) +{ + return 0; +} diff --git a/exam/exam-3 b/exam/exam-3 new file mode 100755 index 0000000000000000000000000000000000000000..cd57f6442df972055d247f29e2c8e979d3012e3e GIT binary patch literal 9632 zcmeHNZ)_Y#6`!>o;uJfvO;SMo={dz!N~`2dlj2hT*da^T#CESf2U)42>H2*3ZFT>2 zx92($28%0Im+PTJM94w`tbS-MR3RgQ6ql}c-2B&!OQDWS*j z&CZ_p_6`$ONPOU)G=JW_H@|uF=I!j=%wGH8uOIGZOlf9pzKJomA4x;Q4_N>;#y*Xt zA#olWct|~~jy_DS)udFjbveR0f&n-mQ^&`uRYd=e>NX~Mn8NlTeN2iuH>0!Wj;FyB%63-j02Q$79iWI+}r! zAMY)RH!cB)C%;#y#=c0_%oxdOso=*8V!>#>AD43Cy;Ow_0q42o6Gn298_B7Z;H%f; zL5UZVAjI!RoJV7PDx)W&j+WoPlEjP2AR%5ZO0pZ4pucSC3 zTq=n;PiIoou#3;=87wd7_3@54>Wt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`jCxIWvmS19Wo9=-Ct5C-gLXR9sdk z=@R`H3LT#{vn?EiHTN0@OMfY3ggMLIH%i5YX106?;x)?VZ%4L{v%97U`>`^^eu}R+ zO5JE%plp${rEVD|TL=3C!C-K$Ip8$VDEo0B6U0R$oy*XDqu}Lv%wfrgBp)W8E<5FU z&{^W!7<2D!9|wN`y6!m=efvPXd!BTGcnq|RgFzbaDao%%{-Wf`5RyMjJo>xmPrm`* ztYB~u$zMStxqD9aC*mP^O!j|W^6vfMo8Td)u7Wm@d-)qazTFX4^zZWVy*@tS^hO?{`L?OoyvX^i4Jf<{hvTa=cBvn25=M3&BzoFqVmwt!zTxZ zI3L8bEh3Eq3iac?^x2DU;@PDeenXEN7r>>GT*sFolTkd+xrpF{)FCZCp%DASP#@<; ziaIeaVjN!vh;oK-y<>>F6T7a&31QerpJs??=e+iz;O;ZS#iQgrTY&Iw6_pk-qmgjE l?Lp}H1Y%==z}@Sd>POq=MBk6HvsCXX&Tdk(VbYqje*y6C!`J`- literal 0 HcmV?d00001 diff --git a/exam/exam-3.cc b/exam/exam-3.cc new file mode 100644 index 0000000..1177899 --- /dev/null +++ b/exam/exam-3.cc @@ -0,0 +1,20 @@ +#include +using namespace std; + +void swap1( int a, int b ) { int c=a; a=b; b=c; } +void swap2( int *a, int *b ) { int c=*a; *a=*b; *b=c; } +void swap3( int &a, int &b ) { int &c=a; a=b; b=c; } + +int main( int argc, char **argv ) +{ + int a, b; + + a = 1; b = 2; swap1(a,b); + cout << "a: " << a << ", " <<"b: " << b << endl; + + a = 1; b = 2; swap2(&a,&b); + cout << "a: " << a << ", " <<"b: " << b << endl; + + a = 1; b = 2; swap3(a,b); + cout << "a: " << a << ", " <<"b: " << b << endl; +} diff --git a/exam/exam-4 b/exam/exam-4 new file mode 100755 index 0000000000000000000000000000000000000000..a155152a7a28dae9f34498c90975adf7cac3daef GIT binary patch literal 9016 zcmeHNU1(fI6h51zCfc;!#tODtyDdh8)i#Az)(16-U2;RyHZ}>AN|^3$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*wz#34%Kp18*x$bz4_k&6eyef3*PZi4(a=h!<2ccqwhsVDC1h{q?VcQ+l1tzxlc)H z+1#r*S~mA8CCJSI7=t+MITYHP` zhW;h_uLijtGKO;h2ZGc;r%CE*Y!4wrtep6S>PDr1@MvG}pi%?MT|MlV{rmVwh^S-7 z-5j?aP1$E4Wiu*@|1yjx3QoQlcja!|7L{|8{;(T%2E$6(StiCsxw` + +struct A { unsigned int color; }; +struct B : public A { }; +struct C : public A { }; +struct D : public B, public C { }; + +int main(int argc, char** argv) +{ +// D d; +// d.color = 3; +// std::cout << d.color << std::endl; + return 0; +} diff --git a/exam/exam-5 b/exam/exam-5 new file mode 100755 index 0000000000000000000000000000000000000000..d8f8869a3c286b4b8492f542a908ed9e16c3580c GIT binary patch literal 9840 zcmeHNU2I%O6`pHvhzoY&ng)^ptzBW{Qk2+^8@W{}UdOk+R*dU=}!puUiYf{I$9geQlzB&tvw9*`=;L&cA9gb@|0kZA+U_sz_; zch}CgsgQWNN1mT=&Y3f3&Yd}TJ#$}w=WqYnDTGxo#6q1AVi%HwhVLx2p(eyWVk9X? zqL0|e?a@csT1i$V+!j$!2L_OG%sw_&DWdu}SGEa*VT#y+^dZBR(ofF$o3hpVRz8f$ zfc+RJ10s&-s?H-~p&Uw?^YatAjizdSElpYaq*-=Ici!l0G<@Q6s?ZIFl=;lp-OQwPGgDcGE1$+tE9Lh3I<&apdaGC`LAxoX%%o)QRC*$tk~6-yMPG-pFEER^e4bn% z!84*tDNkn0mhl#Sy;b^%tMzfO1|(%FUdukm==-YaKwPemenZm+Ntw=ak+{B`%4ZT= z>^pDtHJBd6<@#>h(4;F;PUJRs+1BUrg3)J|iRx6Yue_a1DHGXrI-Akjx9YoK^tA>8 zC~N84jB`VS!$<9b!5~IKLB+Z=3TMoQr{BtLyBl$|6Kw)=^i2cG8I*G1e>2!m$oNq3?v-nHv(jV#_>mN?x zH-C*diMUHiq1|8jC=ui(a&0r+gJ%Zl?hS5%j zeqN>aPB2UD-74=<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public A { }; +struct A3 : public A { }; +struct A4 : public A { }; +struct B : public A1, public A2, public A3, public A4 { }; + +int main(int argc, char** argv) +{ + B b; + return 0; +} diff --git a/exam/exam-6 b/exam/exam-6 new file mode 100755 index 0000000000000000000000000000000000000000..ec3155ea0bb13b9f3c29db77b452f91b8f8f14f2 GIT binary patch literal 9568 zcmeHNUu+yl8K12kasfNB-IN3sgxwNIDN1bWMs5YgPQ2}&>bOVF5vDYnoX=<9qWfd+ z_KXwZ%E$`p>U7dcMWRR`$_t7R5=KZUfj*?9U_Vr?P%G#|9|8jDDpFyU2)R}0@%zor z+Ix4#sq)g7{iONxee-?4`R3c1xxJZv^}V;>-z|jECdASmLWsRc76ccT`cM<%6XcPk zjEy{IK53qMg3?AZ8rf|*;v7Z?QcjqY6OAg$zN=9tG!IwAE~Jm>W+|Q2g0rRDjJN(V z3r7Sw7sp6)n8LtNcAzr`M@Oj@LqVcx;Bc4pBGIOZ{l$!BI zHQuBKAg^8ZBrX0Wi%!AL&1(H-ydP=24&6>ZNDbI%kg}Bfww;@nc5WuG_{QgPQRBrl z2>G2z%2Zm;6cX8#r`7D=hQ^ENNkSfT?f(+z$%2|Eqaza|0X57A1)=AKKR^7E^Mtr8 zNm9-g^0V+u&L;|Zyi#tDci2-G#A%o(zFe15<}$K)E<2Ua$T_Fbf_GT^=etKfI8M%w zNB~pH*?eFcx8Mym;gN5~`)C7RCb5%$mc|>_HsphNjGI4)s3K)H&q-oCa;B6^w)ppq z#`DKSK8UwR_v05*P8GLSS?lwtYCJtnlvxljC}*RT$$U1O&u!s1KHujwUazl!awoj4 zeQqo|{!5=`maxW49v2BSM5{X?gG1i?(!RHRPfzHBye}lwhxQu&|_>7O1iiM*Yd+O-) zxy&?p(%ne(W8+tQvQPi@p*w$Y^}Z7uPrsJ@3}gr;2I}=nKQ1A0t$ZHo!zO>fzm*>x z_Ye}t=#Y3rjz&If8^K^#KoRMGpNPR_z9#&gI)Yw(Me^G91q%k7Fvwk zH9S`pKh#4CB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0000000..ea5284a --- /dev/null +++ b/exam/exam-6.cc @@ -0,0 +1,20 @@ +#include + +struct Foo +{ + Foo(int n) : x(n++), y(n++), z(n++) {} + int x; + int y; + int z; +}; + +int main(int argc, char** argv) +{ + Foo f(3); + + std::cout << "x: " << f.x << std::endl; + std::cout << "y: " << f.y << std::endl; + std::cout << "z: " << f.z << std::endl; + + return 0; +} diff --git a/exam/exam-7 b/exam/exam-7 new file mode 100755 index 0000000000000000000000000000000000000000..d387c7e97a0a85f30f3d1d08380cb24c424e32e3 GIT binary patch literal 9336 zcmeHNU2IfE6rM{96fICHL{XH2A}9tHMN*=M7JKD36sX-25p9O;cH6zWKh5slT2SI9 zRm0LW=>rcWM#Y#IO?)862Z+%WG1Mp#dEDITeeYK zOh&PIU5PknU?^p)xudn%M76If)(I`cH!)o&T1e?cdL5QrD#aVB#9&bMrgn;Qxo1pX zF0zH9lxZi^o}N&Z;ysUm5b8c{;mKZu3XO-5DRS{-G!pBMq@XFq%WAwPZBLnTpP)(p zWfCvhi4JKeI+HLe#XG6-nl%9BsYuF5RCcC9@rY|xidQq&9q$yi zsBf(=FvI+*De&gCgmYerOHPuqJC*E$U$Q5Z!gSmSZ-r|vxIT*J)zfP(Wg;fiyW{Q2 znCx~^lkiq(|2(%S7mkzj>CGu2rR+);EW1f~wIz6zOYthSZ!TUeG?jmr#tY~+lne0~ zw_A$v;z=$N+mW4_M0k>ay&BK+fpQ_cx0 z0PhC(sJBLleH4~por7_&-hq^bya2rFULm3YycOkUB$D^MVqbXth|<{7#-s1x0ERw^ zxQ%O&*nV{;omw5U+gEq&j&(pL-GxLy#sbUBcYdYy)2 zkU0DYk^XD)p3gV)gX6A6;usloA=V^@!-{e1#k_iZ#6|RTKLUOP{0R6F_&-MA1!3iWvig3!WcBZ@um&1GIHh!3*&}!d%t;BDbBJ0#f%f?dE;U^a8educv%kjAm^CoV%ALxc7(EYk=sx#!!&dIw(UYp@QMc#OoH^ESj#+(Q z2HK8yu9~~}HR^@-x5~=x9k&Lie?|a|=RH)xw5shm2US3{KZ3!Eqxn2Xj&Arm(sq3A z;w<$-`jQ5*YFs#gmeslZ@+Gid`AJ6JO*25g)o_s!U9c5dRHL&35Z%_ zWbA1XMsJl-RXMYQ9X$jc`xyEQ;Q+l)BT_k=&Z&B1S~;O-d;cM5--OhC)wSpQtD-6F zUxC3cZU3A$p9=pY*ok0*0Y3tM1pEm25%446N5GGOAAx@-0`r!N?G4We zF|SU_ok3@9IGJ(8)2Z4)Ek_a^vBq%FS+gb_4W*=$3fWG&F>IPG&^^)~O50(XOgpJa zDBjpATLaPzu9IT0x{h~M>TX@OiLtWGrnqKh+XU2Bj$m zMXI?#Z&R^DE1X(8nU?4=vbGV|oKLPXdsw~e`qd4(I$Di^$Z&5+hVbEl?XXEVbh?bo zB`GS?PAKJw&7xe2dHF7 ztMnL;n99V^LS)%H0U8!{|lOAhUza4ow`(3@xlXYy@i5snZ-Bm>kyUA-qSV z?46JBjEOQo%plvsA`g}HxlAi%G|Fn3_k(jQubt<_wCtVhI9m43b+VAl3^WE2{{Rx( zd*?rIQD%kqj|YvEy?eY5Aw#5vqEC?*$|p+X?@Q$I61mK6Jb|~tl^I_}TT0|$i4522 zD#Io4>4K<6x(!L64ZCF0EJCW+cwrWN!cjXs=y9eyM`ZlgdD7T z-nHAIn7s#5G9g3wMx!HwosbDDIbhpDcB_vW)Xr+EmC{bKk&tS2;f`MM9`?wOAJj^c za`Hlx-ZFIEa91lpOE%Ah1|75VdK>0?6>6)X!rT3B@t + +int main(int argc, char** argv) +{ + int x = 0; + int y = 0; + + if (x++ && y++) + { + y += 2; + } + + std::cout << x + y << std::endl; + + return 0; +} diff --git a/exam/exam-8 b/exam/exam-8 new file mode 100755 index 0000000000000000000000000000000000000000..8952ccdfa06e31053bb1c78a6bd783e3ce065024 GIT binary patch literal 8712 zcmeHM-D@0G6hD*QnyseEwiHopWLr!Pwk9cv#)ryo&EOQ181n%!P_FwiO;+~H*$)%7 zu&^kOOE3>U_~yURM}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 0000000..9f0ac98 --- /dev/null +++ b/exam/exam-8.cc @@ -0,0 +1,13 @@ +struct A +{ + A(int x) : n(x) {} + int n; +}; + +int main(int argc, char** argv) +{ +// A a1; + A a2(2); +// A a3(a2); + return 0; +} diff --git a/exam/exam-9 b/exam/exam-9 new file mode 100755 index 0000000000000000000000000000000000000000..b52c6d8a1d33830e1b44832df3ef0303e168988c GIT binary patch literal 9528 zcmeHNZEO@p7@lhj6f96GsHjLm&>{wk0x1SVi(S};3Y9AfVw&OZdhM;=-8Of7wNyz; z8jMHNct0@Vk4R#onD_%tOd!Stgn%Z-kAL_}LNqB65;ep$2%OI|H{0%AOEJX6Kl`Th z@yxvQ%)9T*>`iC(`y1D8&k!O|F2q2Y5MmC3iGqWo7C9jnBA5tLwl!@v_82>Nu(VhL z#c)zYo;q|OWxKJvy;w!HuP!bV8p9MZ4Pm;jmePs#Ipeyee5b4MFsOb*8%10(u1+xE zg;J)SOgKGORLZvz4k1;&)^M@gpi=XV+ebbbi^hARDJYfl#WmkvO+ZY)kI4l4B55aO zCA+mkDc`r6509yY*egZcsE{&~eBDZRN-NoAD_lGt7d2m-CLx|mq>RR7S1Oc<7PLz3 ztD9T!-$hMAjJbA4;XLV6^Q5_{y~(47`JjeW&kJ{cxGCoed6`nA>`B?(uuJxaQW#z- zC+Djxs0;EG%@em=r&1>4GQBSmw&SwLNloCZ)AqUM5qqDL^P|$kDP_0qnZ^_N8cO(x zOZjFM@x?<^*=K6LM%{+k%SXStbBHQZCTva;%aL7~WMqPUZ)-mHnTWl7Gj%_1B4s!| zzRD(!M^5wUWviNb`Ml+c1$}Tw}-AZG#>qQ z%ghabpZRhb%HT?LUYKpP<0Jyt%2Npcx47^7yV=3#Zb0BO7T$?#k()8@3-}}LbVgRL zT(y1`{9=Vs4Vlm`@IFcdMeTz7(oQt7YO}Z96VRgHzQ(w^YXs02-vhn}d=K~@_>VmB zsxY&^nuEXmZVv6QG>0?Q*&Bmj1IvZNXx6xCW;39gwg`I#a~OZ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jZ`$ Lg@rxgT_(gou7Aj` literal 0 HcmV?d00001 diff --git a/exam/exam-9.cc b/exam/exam-9.cc new file mode 100644 index 0000000..071110f --- /dev/null +++ b/exam/exam-9.cc @@ -0,0 +1,13 @@ +#include + +int main(int argc, char** argv) +{ + long x[50]; + // A // memset(x, 0, 50); + // B // memset(x, 0, sizeof(x)); + // C // memset(x, 0, 50 * 4); + // D // memset(x, 0, 50 * sizeof(x)); + + std::cout << "sizeof(x): " << sizeof(x) << std::endl; + memset(x, 0, sizeof(x)); + } diff --git a/page.tmpl b/page.tmpl new file mode 100644 index 0000000..2591bce --- /dev/null +++ b/page.tmpl @@ -0,0 +1,8 @@ +%(head_prefix)s +%(head)s +%(stylesheet)s +%(body_prefix)s +%(body_pre_docinfo)s +%(docinfo)s +%(body)s +%(body_suffix)s diff --git a/pygment.css b/pygment.css new file mode 100644 index 0000000..4f4190b --- /dev/null +++ b/pygment.css @@ -0,0 +1,34 @@ +.hll { background-color: #ffffcc } +.c { font-style: italic } /* Comment */ +.err { border: 1px solid #FF0000 } /* Error */ +.k { font-weight: bold } /* Keyword */ +.cm { font-style: italic } /* Comment.Multiline */ +.c1 { color: #999999; font-style: italic } /* Comment.Single */ +.cs { color: #999999; font-style: italic } /* Comment.Special */ +.ge { font-style: italic } /* Generic.Emph */ +.gh { font-weight: bold } /* Generic.Heading */ +.gp { font-weight: bold } /* Generic.Prompt */ +.gs { font-weight: bold } /* Generic.Strong */ +.gu { font-weight: bold } /* Generic.Subheading */ +.kc { font-weight: bold } /* Keyword.Constant */ +.kd { font-weight: bold } /* Keyword.Declaration */ +.kn { font-weight: bold } /* Keyword.Namespace */ +.kr { font-weight: bold } /* Keyword.Reserved */ +.s { font-style: italic } /* Literal.String */ +.nc { font-weight: bold } /* Name.Class */ +.ni { font-weight: bold } /* Name.Entity */ +.ne { font-weight: bold } /* Name.Exception */ +.nn { font-weight: bold } /* Name.Namespace */ +.nt { font-weight: bold } /* Name.Tag */ +.ow { font-weight: bold } /* Operator.Word */ +.sb { font-style: italic } /* Literal.String.Backtick */ +.sc { font-style: italic } /* Literal.String.Char */ +.sd { font-style: italic } /* Literal.String.Doc */ +.s2 { font-style: italic } /* Literal.String.Double */ +.se { font-weight: bold; font-style: italic } /* Literal.String.Escape */ +.sh { font-style: italic } /* Literal.String.Heredoc */ +.si { font-weight: bold; font-style: italic } /* Literal.String.Interpol */ +.sx { font-style: italic } /* Literal.String.Other */ +.sr { font-style: italic } /* Literal.String.Regex */ +.s1 { font-style: italic } /* Literal.String.Single */ +.ss { font-style: italic } /* Literal.String.Symbol */ diff --git a/rst2html.py b/rst2html.py new file mode 100755 index 0000000..fd72bea --- /dev/null +++ b/rst2html.py @@ -0,0 +1,248 @@ +#!/usr/bin/python +# coding: utf-8 + +# :Author: Georg Brandl; Felix Wiemann; Günter Milde +# :Date: $Date: 2011-08-27 00:23:29 +0200 (Sam, 27. Aug 2011) $ +# :Copyright: This module has been placed in the public domain. +# +# This is a merge of `Using Pygments in ReST documents`_ from the pygments_ +# documentation, and a `proof of concept`_ by Felix Wiemann. +# +# .. class:: borderless +# +# ========== ============================================================= +# 2007-06-01 Removed redundancy from class values. +# 2007-06-04 Merge of successive tokens of same type +# (code taken from pygments.formatters.others). +# 2007-06-05 Separate docutils formatter script +# Use pygments' CSS class names (like the html formatter) +# allowing the use of pygments-produced style sheets. +# 2007-06-07 Merge in the formatting of the parsed tokens +# (misnamed as docutils_formatter) as class DocutilsInterface +# 2007-06-08 Failsave implementation (fallback to a standard literal block +# if pygments not found) +# 2010-11-27 Rename directive from "code-block" to "code". +# Fix fallback if pygments not found. +# Use class-based interface. +# Add "number-lines" option. +# ========== ============================================================= +# +# :: + +"""Define and register a code directive using pygments""" + +# Requirements +# ------------ +# :: + +from docutils import nodes +from docutils.parsers.rst import directives, Directive +from docutils.parsers.rst.roles import set_classes +try: + import pygments + from pygments.lexers import get_lexer_by_name + from pygments.formatters.html import _get_ttype_class + with_pygments = True +except ImportError: + with_pygments = False + +# Customisation +# ------------- +# +# Do not insert inline nodes for the following tokens. +# (You could add e.g. Token.Punctuation like ``['', 'p']``.) :: + +unstyled_tokens = [''] # Token.Text + +# Lexer +# --------- +# +# This interface class combines code from +# pygments.formatters.html and pygments.formatters.others. + +class Lexer(object): + """Parse `code` lines and yield "classified" tokens. + + Arguments + + code -- list of source code lines to parse + language -- formal language the code is written in. + + Merge subsequent tokens of the same token-type. + + Iterating over an instance yields the tokens as ``(ttype_class, value)`` + tuples, where `ttype_class` is taken from pygments.token.STANDARD_TYPES + and corresponds to the class argument used in pygments html output. + """ + + def __init__(self, code, language): + """ + Set up a lexical analyzer for `code` in `language`. + """ + self.code = code + self.language = language + self.lexer = None + # get lexical analyzer for `language`: + if language in ('', 'text'): + return + if not with_pygments: + raise ApplicationError('Cannot highlight code. ' + 'Pygments package not found.') + try: + self.lexer = get_lexer_by_name(self.language) + except pygments.util.ClassNotFound: + raise ApplicationError('Cannot highlight code. ' + 'No Pygments lexer found for "%s".' % language) + + # Since version 1.2. (released Jan 01, 2010) Pygments has a + # TokenMergeFilter. ``self.merge(tokens)`` in __iter__ can be + # replaced by ``self.lexer.add_filter('tokenmerge')`` in __init__. + + def merge(self, tokens): + """Merge subsequent tokens of same token-type. + + Also strip the final '\n' (added by pygments). + """ + tokens = iter(tokens) + (lasttype, lastval) = tokens.next() + for ttype, value in tokens: + if ttype is lasttype: + lastval += value + else: + yield(lasttype, lastval) + (lasttype, lastval) = (ttype, value) + if lastval != '\n': + yield(lasttype, lastval) + + def __iter__(self): + """Parse self.code and yield "classified" tokens + """ + codestring = u'\n'.join(self.code) + if self.lexer is None: + yield [('', codestring)] + return + tokens = pygments.lex(codestring, self.lexer) + for ttype, value in self.merge(tokens): + # yield (ttype, value) # token type objects + yield (_get_ttype_class(ttype), value) # short name strings + + +class NumberLines(object): + """Insert linenumber-tokens in front of every newline. + + Arguments + + tokens -- iterable of ``(ttype_class, value)`` tuples + startline -- first line number + endline -- last line number + + Iterating over an instance yields the tokens preceded by + a ``('ln', '')`` token for every line. + Multi-line tokens from pygments are splitted. """ + + def __init__(self, tokens, startline, endline): + self.tokens = tokens + self.startline = startline + # pad linenumbers, e.g. endline == 100 -> fmt_str = '%3d ' + self.fmt_str = '%%%dd ' % len(str(endline)) + + def __iter__(self): + lineno = self.startline + yield ('ln', self.fmt_str % lineno) + for ttype, value in self.tokens: + lines = value.split('\n') + for line in lines[:-1]: + yield (ttype, line + '\n') + lineno += 1 + yield ('ln', self.fmt_str % lineno) + yield (ttype, lines[-1]) + + +# CodeBlock directive +# -------------------- +# :: + +class CodeBlock(Directive): + """Parse and mark up content of a code block. + """ + optional_arguments = 1 + option_spec = {'class': directives.class_option, + 'name': directives.unchanged, + 'number-lines': directives.unchanged # integer or None + } + has_content = True + + def run(self): + self.assert_has_content() + if self.arguments: + language = self.arguments[0] + else: + language = '' + set_classes(self.options) + classes = ['code', language] + if 'classes' in self.options: + classes.extend(self.options['classes']) + + # TODO: config setting to skip lexical analysis: + ## if document.settings.no_highlight: + ## language = '' + + # set up lexical analyzer + tokens = Lexer(self.content, language) + + if 'number-lines' in self.options: + # optional argument `startline`, defaults to 1 + try: + startline = int(self.options['number-lines'] or 1) + except ValueError: + raise self.error(':number-lines: with non-integer start value') + endline = startline + len(self.content) + # add linenumber filter: + tokens = NumberLines(tokens, startline, endline) + + node = nodes.literal_block('\n'.join(self.content), classes=classes) + self.add_name(node) + + # analyze content and add nodes for every token + for cls, value in tokens: + # print (cls, value) + if cls in unstyled_tokens: + # insert as Text to decrease the verbosity of the output. + node += nodes.Text(value, value) + else: + node += nodes.inline(value, value, classes=[cls]) + + return [node] + + +# Register Directive +# ------------------ +# :: + +directives.register_directive('code', CodeBlock) + +# .. _doctutils: http://docutils.sf.net/ +# .. _pygments: http://pygments.org/ +# .. _Using Pygments in ReST documents: http://pygments.org/docs/rstdirective/ +# .. _proof of concept: +# http://article.gmane.org/gmane.text.docutils.user/3689 +# +# Test output +# ----------- +# +# If called from the command line, call the docutils publisher to render the +# input:: + +if __name__ == '__main__': + from docutils.core import publish_cmdline, default_description + description = 'code-block directive test output' + default_description + try: + import locale + locale.setlocale(locale.LC_ALL, '') + except: + pass + # Uncomment the desired output format: + # publish_cmdline(writer_name='pseudoxml', description=description) + # publish_cmdline(writer_name='xml', description=description) + publish_cmdline(writer_name='html', description=description) + # publish_cmdline(writer_name='latex', description=description) diff --git a/sources/.DS_Store b/sources/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..d1d946d5f2e655c15e77b9815f9d9963f40958cc GIT binary patch literal 6148 zcmeHK%Syvg5Iv(=6x|fuxXjXxLVa#Sse%hP`UBcnQ7i;ny3c3$QGS4bqi5z0l9GsI zBT{By=G@nukQ45mTmUj&J&u4OfB{`G+hOQ1omX$!mXGM97{@aXQKG^Mi`MEG2n9lc z|E7TM-97Hv1sZ2iunOl_9;o-8L_ zEOOhE<+PLKqbJK*7mMlg)?VvD3WNfoz_$W=KIC-8!m&1w*JPG~6%UXHDyrFfri#<^S@#KN&o$Prrn N2$&2JLV-V3;0sZ4j`#oo literal 0 HcmV?d00001 diff --git a/sources/Makefile b/sources/Makefile new file mode 100644 index 0000000..4856287 --- /dev/null +++ b/sources/Makefile @@ -0,0 +1,35 @@ +# Copyright (C) 2012 Nicolas P. Rougier +# +# This program is free software: you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation, either version 3 of the License, or (at your option) any later +# version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT +# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS +# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. + +# You should have received a copy of the GNU General Public License along with +# this program. If not, see . +PLATFORM = $(shell uname) +CXX = g++ +CXXFLAGS = -Wall -ansi -pedantic + +SOURCES:= $(wildcard *.cc) +TARGETS := $(SOURCES:.cc=) + +all: $(TARGETS) + + +define template +$(1): $(1).cc + @echo "Building $$@... " + @$(CXX) $(1).cc $(CXXFLAGS) -o $$@ +endef +$(foreach target,$(TARGETS),$(eval $(call template,$(target)))) + +clean: + @-rm -f $(TARGETS) + +distclean: clean + @-rm -f *~ diff --git a/sources/crash-course-2.1.cc b/sources/crash-course-2.1.cc new file mode 100644 index 0000000..1b73c97 --- /dev/null +++ b/sources/crash-course-2.1.cc @@ -0,0 +1,41 @@ +/* + * Copyright (C) 2012 Nicolas P. Rougier + * + * This program is free software: you can redistribute it and/or modify it under + * the terms of the GNU General Public License as published by the Free Software + * Foundation, either version 3 of the License, or (at your option) any later + * version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + * + * You should have received a copy of the GNU General Public License along with + * this program. If not, see . + */ +int main( int argc, char **argv ) +{ + // Pointer to a char + char * p1 = new char; + + // A constant pointer to a char + char * const p2 = p1; + + // A pointer to a constant char + const char * p3 = p1; + + // A constant pointer to a constant char + const char * const p4 = p2; + + // A reference to a char + char & r1 = *p2; + + // A reference to a constant char: + const char & r2 = *p4; + + // To have no warning at compilation for unused variables + if( *p3 == r1 ) { } + if( *p3 == r2 ) { } + +} diff --git a/sources/crash-course-2.2.cc b/sources/crash-course-2.2.cc new file mode 100644 index 0000000..db765fe --- /dev/null +++ b/sources/crash-course-2.2.cc @@ -0,0 +1,39 @@ +/* + * Copyright (C) 2012 Nicolas P. Rougier + * + * This program is free software: you can redistribute it and/or modify it under + * the terms of the GNU General Public License as published by the Free Software + * Foundation, either version 3 of the License, or (at your option) any later + * version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + * + * You should have received a copy of the GNU General Public License along with + * this program. If not, see . + */ +#include + +int main( int argc, char **argv ) +{ + const size_t n = 2; + int **array = new int *[n]; + + for( size_t i=0; i. + */ +#include + +class Point { +public: + Point( void ) : _x(0.0), _y(0.0) { }; + + static Point cartesian( const float x, const float y ) + { return Point( x, y ); } + + static Point polar( const float rho, const float theta ) + { return Point( rho*std::cos(theta), rho*std::sin(theta) ); } + +private: + Point( const float x, const float y ) : _x(x), _y(y) { }; + float _x; + float _y; +}; + + +int main( int argc, char **argv ) +{ + Point p1 = Point::cartesian(5.7, 1.2); + Point p2 = Point::polar(5.7, 1.2); + return 0; +} diff --git a/sources/crash-course-3.4.cc b/sources/crash-course-3.4.cc new file mode 100644 index 0000000..6103f11 --- /dev/null +++ b/sources/crash-course-3.4.cc @@ -0,0 +1,51 @@ +/* + * Copyright (C) 2012 Nicolas P. Rougier + * + * This program is free software: you can redistribute it and/or modify it under + * the terms of the GNU General Public License as published by the Free Software + * Foundation, either version 3 of the License, or (at your option) any later + * version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + * + * You should have received a copy of the GNU General Public License along with + * this program. If not, see . + */ +#include +#include + +class Point { +public: + Point( void ) : _x(0.0), _y(0.0) { }; + + static Point cartesian( const float x, const float y ) + { return Point( x, y ); } + + static Point polar( const float rho, const float theta ) + { return Point( rho*std::cos(theta), rho*std::sin(theta) ); } + + friend std::istream & operator >> (std::istream & input, Point & that) + { return input >> that._x >> that._y; } + + friend std::ostream & operator << (std::ostream & output, Point & that) + { return output << "(" << that._x << ", " << that._y << ")"; } + +private: + Point( const float x, const float y ) : _x(x), _y(y) { }; + float _x; + float _y; +}; + + +int main( int argc, char **argv ) +{ + Point p; + std::cout << "Enter a new point x y: "; + std::cin >> p; + std::cout << "p = " << p << std::endl; + + return 0; +} diff --git a/sources/crash-course-3.5.cc b/sources/crash-course-3.5.cc new file mode 100644 index 0000000..33bf205 --- /dev/null +++ b/sources/crash-course-3.5.cc @@ -0,0 +1,38 @@ +/* + * Copyright (C) 2012 Nicolas P. Rougier + * + * This program is free software: you can redistribute it and/or modify it under + * the terms of the GNU General Public License as published by the Free Software + * Foundation, either version 3 of the License, or (at your option) any later + * version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + * + * You should have received a copy of the GNU General Public License along with + * this program. If not, see . + */ +#include + +class Foo { +public: + Foo ( void ) + { }; + + Foo & method1( void ) + { return *this; } + + void method2( void ) + { } +}; + + +int main( int argc, char **argv ) +{ + Foo foo; + foo.method1().method2(); + + return 0; +} diff --git a/sources/crash-course-4.1.cc b/sources/crash-course-4.1.cc new file mode 100644 index 0000000..fdb216d --- /dev/null +++ b/sources/crash-course-4.1.cc @@ -0,0 +1,43 @@ +/* + * Copyright (C) 2012 Nicolas P. Rougier + * + * This program is free software: you can redistribute it and/or modify it under + * the terms of the GNU General Public License as published by the Free Software + * Foundation, either version 3 of the License, or (at your option) any later + * version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + * + * You should have received a copy of the GNU General Public License along with + * this program. If not, see . + */ +#include + +class Foo { +public: + Foo( void ) + { std::cout << "Foo constructor called" << std::endl;}; + + virtual ~Foo( void ) + { std::cout << "Foo destructor called" << std::endl;}; +}; + +class Bar : public Foo { +public: + Bar( void ) + { std::cout << "Bar constructor called" << std::endl;}; + + ~Bar( void ) + { std::cout << "Bar destructor called" << std::endl;}; +}; + +int main( int argc, char **argv ) +{ + Foo * foo = new Bar(); + delete foo; + + return 0; +} diff --git a/sources/crash-course-4.2.cc b/sources/crash-course-4.2.cc new file mode 100644 index 0000000..cb8b21b --- /dev/null +++ b/sources/crash-course-4.2.cc @@ -0,0 +1,36 @@ +/* + * Copyright (C) 2012 Nicolas P. Rougier + * + * This program is free software: you can redistribute it and/or modify it under + * the terms of the GNU General Public License as published by the Free Software + * Foundation, either version 3 of the License, or (at your option) any later + * version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + * + * You should have received a copy of the GNU General Public License along with + * this program. If not, see . + */ +#include + +void foo( void ) +{ std::cout << "::foo() called" << std::endl;} + +class Foo { +public: + Foo( void ) + { ::foo(); foo(); } + + void foo( void ) + { std::cout << "Foo::foo() called" << std::endl;}; + +}; + +int main( int argc, char **argv ) +{ + Foo foo; + return 0; +} diff --git a/sources/crash-course-4.3.cc b/sources/crash-course-4.3.cc new file mode 100644 index 0000000..52c189b --- /dev/null +++ b/sources/crash-course-4.3.cc @@ -0,0 +1,54 @@ +/* + * Copyright (C) 2012 Nicolas P. Rougier + * + * This program is free software: you can redistribute it and/or modify it under + * the terms of the GNU General Public License as published by the Free Software + * Foundation, either version 3 of the License, or (at your option) any later + * version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + * + * You should have received a copy of the GNU General Public License along with + * this program. If not, see . + */ +#include +#include + + +class Real { +public: + Real( float value = 0 ) : _value(value) { }; + virtual Real operator+(Real &other) { return Real(_value + other._value); } + virtual Real operator-(Real &other) { return Real(_value - other._value); } + virtual Real operator*(Real &other) { return Real(_value * other._value); } + virtual Real operator/(Real &other) { return Real(_value / other._value); } + friend std::ostream& operator<< ( std::ostream& output, Real const & that ) + { return output << that._value; } +protected: + float _value; +}; + +class Integer : public Real { +public: + Integer( int value = 0 ) : Real(int(round(value))) { }; +protected: + int _value; +}; + + + +int main( int argc, char **argv ) +{ + Real r1(1.23), r2(4.56); + Integer i1(1), i2(2); + + std::cout << i1+i2 << " " << std::endl; + std::cout << r1+r2 << " " << std::endl; + std::cout << r1+i2 << " " << std::endl; + std::cout << i1+r2 << " " << std::endl; + + return 0; +} diff --git a/sources/crash-course-4.4.cc b/sources/crash-course-4.4.cc new file mode 100644 index 0000000..2b778c9 --- /dev/null +++ b/sources/crash-course-4.4.cc @@ -0,0 +1,55 @@ +/* + * Copyright (C) 2012 Nicolas P. Rougier + * + * This program is free software: you can redistribute it and/or modify it under + * the terms of the GNU General Public License as published by the Free Software + * Foundation, either version 3 of the License, or (at your option) any later + * version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + * + * You should have received a copy of the GNU General Public License along with + * this program. If not, see . + */ +#include + +class Singleton +{ + +public: + static Singleton * instance( void ) + { + if( !_instance ) + { + _instance = new Singleton; + } + return _instance; + } + +private: + Singleton( void ) + { }; + + Singleton( Singleton const & other ) + { }; + + Singleton & operator=( Singleton const & other ) + { + return *this; + }; + + static Singleton* _instance; +}; + +Singleton *Singleton::_instance = 0; + +int main( int argc, char **argv ) +{ + Singleton *singleton = Singleton::instance(); + + delete singleton; + return 0; +} diff --git a/sources/crash-course-4.5.cc b/sources/crash-course-4.5.cc new file mode 100644 index 0000000..b597dfb --- /dev/null +++ b/sources/crash-course-4.5.cc @@ -0,0 +1,33 @@ +/* + * Copyright (C) 2012 Nicolas P. Rougier + * + * This program is free software: you can redistribute it and/or modify it under + * the terms of the GNU General Public License as published by the Free Software + * Foundation, either version 3 of the License, or (at your option) any later + * version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + * + * You should have received a copy of the GNU General Public License along with + * this program. If not, see . + */ +#include + +class Functor +{ + int _value; +public: + Functor( const int value ) : _value( value ) { } + int operator()( const int value ) { return _value+value; } +}; + +int main( int argc, char **argv ) +{ + Functor functor(1); + std::cout << "functor(3) = " << functor(3) << std::endl; + + return 0; +} diff --git a/sources/crash-course-5.1.cc b/sources/crash-course-5.1.cc new file mode 100644 index 0000000..1826392 --- /dev/null +++ b/sources/crash-course-5.1.cc @@ -0,0 +1,36 @@ +/* + * Copyright (C) 2012 Nicolas P. Rougier + * + * This program is free software: you can redistribute it and/or modify it under + * the terms of the GNU General Public License as published by the Free Software + * Foundation, either version 3 of the License, or (at your option) any later + * version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + * + * You should have received a copy of the GNU General Public License along with + * this program. If not, see . + */ +#include +#include + +class FooException : public std::runtime_error { +public: + FooException( void ) : std::runtime_error("FooException") + { } +}; + +class Foo { +public: + Foo( void ) + { throw new FooException; } +}; + +int main( int argc, char **argv ) +{ + Foo *foo = new Foo; + return 0; +} diff --git a/sources/crash-course-5.2.cc b/sources/crash-course-5.2.cc new file mode 100644 index 0000000..2f272cd --- /dev/null +++ b/sources/crash-course-5.2.cc @@ -0,0 +1,75 @@ +/* + * Copyright (C) 2012 Nicolas P. Rougier + * + * This program is free software: you can redistribute it and/or modify it under + * the terms of the GNU General Public License as published by the Free Software + * Foundation, either version 3 of the License, or (at your option) any later + * version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + * + * You should have received a copy of the GNU General Public License along with + * this program. If not, see . + */ +#include +#include +#include + +class Foo +{ virtual void method( void ) { } }; + +class Bar : public Foo +{ }; + +void unexpected( void ) +{ throw; } + +void function( void ) throw( int, std::bad_exception ) +{ throw 'x'; } + + +int main( int argc, char **argv ) +{ + + // Bad alloc + try + { + int * array = new int[-1]; + int i = 0; + i = array[0]; + } + catch( std::bad_alloc & e ) + { + std::cerr << "bad_alloc caught: " << e.what() << std::endl; + } + + // Bad cast + try + { + Foo f; + Bar & b = dynamic_cast( f ); + } + catch( std::bad_cast & e ) + { + std::cerr << "bad_cast caught: " << e.what() << std::endl; + } + + // Bad exception + std::set_unexpected( unexpected ); + try { + function(); + } + catch( int ) + { + std::cerr << "caught int" << std::endl; + } + catch( std::bad_exception e ) + { + std::cerr << "bad_exception caught " << e.what() << std::endl; + } + + return 0; +} diff --git a/sources/crash-course-5.3.cc b/sources/crash-course-5.3.cc new file mode 100644 index 0000000..8220ed0 --- /dev/null +++ b/sources/crash-course-5.3.cc @@ -0,0 +1,40 @@ +/* + * Copyright (C) 2012 Nicolas P. Rougier + * + * This program is free software: you can redistribute it and/or modify it under + * the terms of the GNU General Public License as published by the Free Software + * Foundation, either version 3 of the License, or (at your option) any later + * version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + * + * You should have received a copy of the GNU General Public License along with + * this program. If not, see . + */ +#include +#include + +class DivideByZero : public std::runtime_error { +public: + DivideByZero( void ) : std::runtime_error("DivideByZero") + { } +}; + +const double divide( const double a, const double b ) +{ + if( b == 0 ) + { + throw DivideByZero(); + } + return a/b; +} + +int main( int argc, char **argv ) +{ + divide(5,3); + divide(5,0); + return 0; +} diff --git a/sources/crash-course-5.4.cc b/sources/crash-course-5.4.cc new file mode 100644 index 0000000..c261c97 --- /dev/null +++ b/sources/crash-course-5.4.cc @@ -0,0 +1,82 @@ +/* + * Copyright (C) 2012 Nicolas P. Rougier + * + * This program is free software: you can redistribute it and/or modify it under + * the terms of the GNU General Public License as published by the Free Software + * Foundation, either version 3 of the License, or (at your option) any later + * version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + * + * You should have received a copy of the GNU General Public License along with + * this program. If not, see . + */ +#include +#include +#include + +struct DivideByZero : public std::runtime_error +{ DivideByZero( void ) : std::runtime_error("DivideByZero") { } }; + +struct OverflowError : public std::runtime_error +{ OverflowError( void ) : std::runtime_error("OverflowError") { } }; + +struct UnderflowError : public std::runtime_error +{ UnderflowError( void ) : std::runtime_error("UnderflowError") { } }; + + +class Integer { +public: + Integer( int value = 0 ) : _value(value) { }; + + virtual Integer operator+(Integer &other) + { + unsigned char result = _value+other._value; + if( result < _value ) + { throw new OverflowError; } + return Integer(result); + } + + virtual Integer operator-(Integer &other) + { + unsigned char result = _value-other._value; + if( result > _value ) + { throw new UnderflowError; } + return Integer(result); + } + + virtual Integer operator*(Integer &other) + { + unsigned char result = _value * other._value; + if((_value > 1) and (other._value >1 ) and ( result < _value )) + { throw new OverflowError; } + return Integer(result); + } + + virtual Integer operator/(Integer &other) + { + if( other._value == 0 ) + { throw new DivideByZero; } + + return Integer(_value / other._value); + } + + friend std::ostream& operator<< ( std::ostream& output, Integer const & that ) + { return output << that._value; } +protected: + unsigned char _value; +}; + +int main( int argc, char **argv ) +{ + Integer a(129), b(128), zero(0); + + Integer c(a+b); // overflow + Integer c(b-a); // underflow + Integer c(a/zeor); // divide by zero + + return 0; +} diff --git a/stylesheet.css b/stylesheet.css new file mode 100644 index 0000000..002ba38 --- /dev/null +++ b/stylesheet.css @@ -0,0 +1,70 @@ +@import url("pygment.css"); + +pre.code { + margin: 0; + margin-left: 20px; + padding: 10px; + line-height: 1.1em; + background-color: #f9f9f9; + border: 1px solid #ccc; + display:inline-block; + min-width: 50%; +} + +body { + font-family: sans-serif; + width: 1000px; + padding: 10px; + margin: 0 auto; + font-size: 1.0em; + line-height: 1.25em; + color: #282828; + +} + +a { + color: purple; + text-decoration: none; +} + +h1, h2, h3 { + font-family: "Gill Sans", "Trebuchet MS", Calibri, sans-serif; + font-weight: 400; +} + + +h1 { + font-family: "Gill Sans", "Trebuchet MS", Calibri, sans-serif; + font-size: 150%; + font-weight: 400; + color: #fff; + background-color: #bbbbff; + line-height: 1.em; + padding: 8px; + border-radius: 5px; + margin-top: 3em; +} + +h1.title { + margin-top: 1em; + margin-bottom: 0em; + font-size: 250%; + color: #000000; + background: #ffffff; + border-radius: 0; +} + +h2 { + font-family: "Gill Sans", "Trebuchet MS", Calibri, sans-serif; + font-size: 125%; + font-weight: 400; + border-left: 5px solid #ddddff; + line-height: 1.em; + padding: 4px; +} + +th { + text-align:left; + padding-right: .5em; + padding-left: .5em; +} \ No newline at end of file