Giter Site home page Giter Site logo

cpp-crash-course's Introduction

C++ crash course for C programmers

Author

Nicolas P. Rougier

Sources

crash-course.rst

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.

  • 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 <iostream> for input/output operations (see stream section for explanation).

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).

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.

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.

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.

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).

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

For constants, prefer the const notation:

For macros, prefer the inline notation:

Mixing C and C++

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

  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.

solution: crash-course-2.2.cc

  1. Write a function that swap two integers, then two pointers.

solution: crash-course-2.3.cc

  1. Is this legal ?

solution: crash-course-2.4.cc

  1. Write a const correct division function.

solution: crash-course-2.5.cc

  1. 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 might 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.

Constructors

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

Destructor

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

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

It's cheaper, better and faster.

Operator overloading

Friends

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

Exercises

  1. Why the following code doesn't compile ?

    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.

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).

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.

Multiple inheritance

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

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 eliminate the problem by explicitly specifying the data origin (e.g. Bar1::data) or by using virtual inheritance in Bar1 and Bar2.

Exercises

  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:

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:

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

Exercises

  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 through 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:

Class input/output

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

Working with files

Working with strings

Exercises

  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 <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 parameters

There are three possible template types:

Template function

Template class

Template specialization

Exercises

  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.

Iterators

Iterators are a convenient tool to iterate over a container:

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.

Exercises

  1. Write a template stack class using the STL vector class
  2. Write a generic vector class with iterators and benchmark it against the STL vector class

cpp-crash-course's People

Contributors

endolith avatar lepisma avatar rougier avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

cpp-crash-course's Issues

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.