SlideShare a Scribd company logo
Exploring C++
Presenter:- Subhendra Basu (SysTools Team)
Background Check
!   Familiarity with basic imperative programming
concepts
!   Variables (scoping, global/local)
!   Loops
!   Functions and function abstraction
!   Prior experience with OOP and knowledge of basic
OOP concepts (inheritance, overloading, etc.)
Session Outline**
!   A brief overview of basic
C++ concepts
!   Overview of STL
!   Overview of Boost
!   Templates
!   Exception Handling
!   Best Practices
!   Design Patterns
!   Web Programming
! gcov and cppunit
!   Questions and References
**This Talk is not meant to be a
exhaustive reference to C++ but just an
overview of the Basics
Which Programming
Language is the fastest ?
http://shootout.alioth.debian.org/u32q/which-programming-languages-are-fastest.php
Binary Code
Assembly Languages
Procedural Languages (C, Fortran, COBOL…)
OO Languages ( C++, Java, Python…)
Declarative languages (Haskell, ML, Prolog…)
?
Towards a higher level of abstraction
Current Status of C++
!   Current day C++ cannot be regarded as “the language
C with classes”
!   C++ is a federation of languages that supports
!   Procedural
!   Object Oriented
!   Functional
!   Generic
! Metaprogramming features
Primary Programming Paradigms
in C++
!   C : Blocks, Statements, Preprocessor, Built-in Data Types,
Arrays, Pointers
!   Object Oriented C++ : classes, encapsulation, inheritance,
polymorphism, virtual functions (dynamic binding)
!   Template C++ : Generic Programming part of C++ (also
known as Template Metaprogramming)
!   The Standard Template Library
Caution: Rules for Effective C++ Programming vary depending on the
part of C++ you are using
Section I:
C++ Basics through Best Practices
{Const, Enum, Inline} vs #define
!   Prefer the compiler to the preprocessor
!   Defining a constant or a macro through a hash define
is risky. Compiler errors may point to the value of the
constant and not the variable used to define the
constant making debugging difficult. Instead use
‘const’ or ‘enum’
!   Macros can be rewritten as inline function to avoid
side-effects
The ‘enum’ hack
Consider the code:
Class GamePlayer {
private:
static const int NumTurns = 5;
enum { NumTurns = 5 };
int scores[NumTurns];
…
}
Move over C macros
// call f with maximum of a and b
#define CALL_WITH_MAX(a,b) f((a) > (b) ? (a):(b))
int a=5; b=0;
CALL_WITH_MAX(++a, b); //a is incremented twice
CALL_WITH_MAX(++a, b+10); //a is incremented once
Better way:
template <typename T>
inline void callWithMax(const T& a, const T& b){
f(a>b?a:b);
}
Pointers vs References
Pointers
!   Can be null
!   May not be initialized at
the point of definition
!   Can be assigned to
different objects at
different points of time.
References
!   Nothing called as a “null”
reference. Always points to an
object
!   It is compulsory to initialize a
reference when defining it
!   The object it points to cannot
be changed on the fly. It keeps
pointing to the value it was
initialized with.
!   More efficient to use than
pointers as there need not be
any run-time type checking to
validate whether it is null or
not
Prefer C++ style casts
!   Easier to parse for humans and tools
!   Allows compilers to catch casting errors which
otherwise would go undetected
!   Four types of casting are supported:
! static_cast
! const_cast
! reinterpret_cast
! dynamic_cast
Use const whenever possible
!   Declaring something ‘const’ helps compilers detect usage
errors. const can be applied to objects at any scope, to
function parameters and return types, and to member
functions as a whole.
!   Compilers enforce bitwise or physical constness, but you
should program using logical or conceptual constness
!   When const and non-cost member functions have essentially
identical implementation, code duplication can be avoided
by having the non-const version call the const version
Make sure objects are initialized
before they are used
!   Reading uninitialized values yields undefined behavior
!   Manually initialize objects of built-in type, because C++ only
sometimes initializes them itself.
!   In a constructor, prefer use of the member initialization list
to assignment inside the body of the constructor. List data
members in the initialization list in the same order they’re
declared in a class.
!   Avoid initialization order problems across translation units
by replacing non-local static objects with local static objects
Never treat Arrays Polymorphically
!   The result of deleting an array of derived class objects
through a base class pointer is undefined.
!   Polymorphism and pointer arithmetic don’t mix
Classes
!   A class is like a cookie cutter; it defines the shape of the
objects
!   Objects are like cookies; they are instances of the class
What C++ silently writes and calls
!   Defining an empty class incites the compiler to declare its
own versions of copy constructor, copy assignment operator,
and a destructor and also a default constructor. All these
functions will be both public and inline.
!   These functions are generated only if they are needed
!   E.g. class Empty {};
Empty e1; //default constructor
//destructor
Empty e2(e1); //copy constructor
E2=e1; copy assignment operator
Explicitly disallow the use of
compiler-generated functions you
do not want
!   Declare the functions (Copy constructor/assignment
operator) but declare them private.
!   But member and friend functions still have access to
this
!   So declare them but don’t define them. (gives a link
time error when called)
!   Possible to move the link time error to compile time.
!   Privately Inherit from a class that is uncopyable.
(‘noncopyable’ in Boost in boost/utility.hpp)
1. Declare destructors virtual in polymorphic base
classes
2. Avoid default constructors where they are not
needed
3. Prevent exceptions from leaving destructors
4. Never call virtual functions during construction
or destruction
5. Have assignment operators return a reference to
*this
6. Handle assignment to self in operator=
7. Copy all parts of an object
Miscellaneous best practices in C++
Inheriatance and Access to
Base Classes
Class X: public B { /**/}
Class Y: protected B { /**/}
Class Z: private B { /**/}
!   When B is a public base, its public members can be used by
any function. Its protected members can be used by
members and friends of D and members and friends of
classes derived from D. Any function can convert a D* to a
B*
!   When B is a protected base, its public and protected
members can be used only by member functions and friends
of classes derived from D and by member functions and
friends of classes derived from D. Only friends and
members of D and friends and members of classes derived
from D can convert D* to B*
!   When B is a private base, its public and protected members
can be used only by member functions and friends of D.
Only friends and members of D can convert D* to B*
Memory Management : auto_ptr
!   Prevent memory leaks by using auto_ptr (smart pointer)
whose destructor calls delete on what it points to.
std::auto_ptr<Investment>pInv(createInvestment());
o  There should not be more than one auto_ptr pointing to
an object as this would lead to multiple deletion and
undefined behavior
o  auto_ptrs have the property that if they are copied using
copy constructor or copy assignment operator, this sets them
to null and the copying pointer assumes sole ownership of
the resource
auto_ptr copying example
std::auto_ptr<Investment> pInv1(createInvestment()); //
pInv1 points to the object returned from
createInvestment
std::auto_ptr<Investment> pInv2(pInv1);
//pInv2 points to the object, pInv1is null
pInv1 = pInv2;
Memory Management: shared_ptr
!   A reference counting smart pointer (RCSP) keeps track of
how many objects point to a particular resource and
automatically deletes the resource when nobody is pointing
to it any longer. RCSPs offer behavior similar to garbage
collection.
!   TR1’s shared::ptr and boost::shared_ptr are examples of
RCSPs
!   Both auto_ptr and tr1::shared_ptr use delete in their
destructors, not delete[] so cannot be used with dynamically
allocated arrays.
!   However Boost has boost::scoped_array and
Boost::shared_array have the required behavior
Section II :
Template Metaprogramming
What are templates and why
Templates ?
!   Templates are functions or classes written for one or
more types not yet specified
!   Extensive Application, the C++ STL library makes
heavy use of templates
!   It is usually a good idea to debug a particular class,
such as String, before turning it into a template
String<C>. This is done for ease of debugging
Template Instantiation
!   The process of generating a class declaration from a
template class and a template argument is called
template instantiation
!   A version of a template for a particular template
argument is called a specialization
!   Templates provide a powerful way of generating code
from relatively short definitions. So it has to be used
with caution lest the memory will be flooded by almost
identical function definitions
Function Templates
!   Function templates are essential for writing generic
algorithms to be applied to a wide variety of container types.
The ability to deduce the template arguments for a call from
the function arguments is crucial.
!   However class template parameters are never deduced. This
is because the flexibility provided by several constructors for
a class make such a deduction impossible in many cases and
obscure in many more.
!   Example:
template <class T> void sort(vector<T>& v) {
//…
}
Function Template overloading
!   It is possible to declare several function templates with the same name and even
declare a combination of function templates and ordinary functions with the same
name.
!   Example:
template<class T> T sqrt(T);
template<class T> complex<T> sqrt(complex<T>);
double sqrt(double);
void f(complex<double> z)
{
sqrt(2); //sqrt<int> (int)
sqrt(2.0); //sqrt(double)
sqrt(z); //sqrt<double>(complex<double>)
}
Using template arguments to
specify policy
!   Consider string sorting program. Three concepts are
involved: string, element type and the comparison “policy”.
!   Take for example, sorting swedish names:
template<class T, class C>
int compare(const String<T>& str1, const String<T>& str2) {
for (int i=0; i<str1.length() && i<str2.length(); i++) {
if (!C::eq(str1[i], str2[i])) return C::lt(str1[i],str2[i])? -1:1;
return str1.length()-str2.length();
}
Sorting Policy (contd)
The Comparison Policy:
template<class T> class Cmp {
public:
static int eq(T a, T b) {return a==b;}
static int lt(T a, T b) { return a<b;}
};
class Literate {
public:
static int eq(char a, char b) {return
a==b;}
static int lt(char, char); //table
lookup based on character value
};
Void f(String<char> swede1, String<char>
swede2)
{
compare<char, Cmp<char> (swede1, swede2);
compare(char, Literate>(swede1, swede2);
}
Default Template Parameters
template<class T, class C = Cmp<T> >
Int compare(const String<T>& str1, const String<T>& str2) {
//…
}
Void f(String<char> swede1, String<char> swede2) {
Compare(swede1, swede2); //use Cmp<char>
}
Template Specialization
!   By default, a template gives a single definition to be
used for every template argument that is possible.
!   In template specialization, an alternative definition is
provided for a type supplied by the user. This increases
run-time efficiency by avoiding code bloat and
maximizing the amount of shared code
Complete Specialization
Template<> class Vector <void*> {
void** p;
//
void*& operator[](int i);
}
Partial Specialization
Template<class T>class Vector<T*>: private Vector<void*>{
};
Vector<Shape*> vps; //T= Shape
Vector<int**> vppi; // T=int*
Order of Specialization
Template<class T>class Vector; //general
Template<class T>class Vector<T*>; specialized for any
pointer
Template<> class Vector<void*>; //specialized for void*
Section III:
Exception Handling
Exceptions
!   An exception is an object of some class representing an
exceptional occurrence.
!   Code that detects an error “throws” an object
!   A piece of code expresses its desire to handle exception
by a catch clause.
!   The effect of a “throw” is to unwind the stack until a
suitable “catch” is found
Catching Exceptions
Void f() {
try {
throw E();
}
catch(H) {
}
}
Catching Exceptions
(conditions)
The handler is invoked:
1.  If H is the same type as E
2.  If H is an unambiguous base of E
3.  If H and E are pointer types and [1] or [2] holds for the
types to which they refer
4.  If H is a reference and [1] or [2] holds for the type to
which H refers
Re-Throw
Void h() {
try {
//code that might throw Math Errors
}
catch(Matherr) {
if (can handle_it_completely) {
// handle the Matherr
return;
} else {
throw; //rethrow the exception
}
}
}
Catch Every Exception
void m() {
try {
}
catch(…) {
throw;
}
Section II :
Overview of STL
STL Basics
!   STL stands for Standard Template Library. STL is the
invention of Dave Musser, Alex Stepanov and Meng
Lee.
!   The main components of STL are: Containers,
Iterators and Algorithms
!   Containers are used to manage objects of a certain
kind. Iterators are used to step through the containers.
Algorithms are used to process the above collections of
objects
STL Components
Container
Container
Container
Algorithms
Iterat
or
Iterat
or
Containers
!   There are two kinds of containers:
!   Sequence Containers: These are ordered collections
where each element has a certain position.
STL has three predefined sequence containers: dequeue,
vector and list
!   Associative Containers: These are sorted collections in
which the position of the element depends on its value
due to a certain sorting criterion. STL ahs four
predefined container classes: set, multiset, map,
multimap
Iterator
iterating over elements of a list
Begin() End()
Pos++
Set with six elements
4
2 6
1 3 5
Section III
BOOST
Library I: smart_ptr
!   Automatic lifetime management of objects with
shared_ptr makes shared ownership of resources
effective and safe
!   Safe observation of shared resources through weak_ptr
avoids dangling pointers
!   Scoped resources using scoped_ptr and scoped_array
make the code easier to write and maintain, helps in
writing exception free code
Boost/scoped_ptr.hpp
!   Boost::Scoped_ptr is used to ensure the proper
deletion of a dynamically allocated object.
! Scoped_ptr is similar to auto_ptr but it doesn’t transfer
ownership as auto_ptr does
!   A scoped ptr cannot be copied or assigned at all
Caution: Never ever store auto_ptr in standard library
containers. Usually you get compiler error. If not, then
you are in trouble.
Scoped_ptr = const auto_ptr ?
!  The difference is that a scoped
pointer can be reset, effectively
deleting and replacing the
pointee when needed
Boost/scoped_array.hpp
!  Scoped arrays do for arrays what
scoped_ptr do for pointers to
single objects
Boost/shared_ptr.hpp
!   It is a reference counted smart pointer that eliminates
the need to write complicated logic to control the
lifetime of objects shared among two or more objects.
!   RCSPs can be categorized as “intrusive” and “non-
intrusive”. The former expects the classes which it
manages to provide certain functionality to manage the
reference count
Boost/shared_array.hpp
! Shared_arrays is a smart
pointer that enables shared
ownership of arrays
Library II: Conversion
!   Understandable, maintainable and consistent
polymorphic conversions
!   Static downcasting using safer constructs than
static_cast
!   Range preserving numeric conversions that ensure
correct value logic and less time debugging
!   Correct and reusable lexical conversions that lead to
less time coding
Polymorphic_cast
!   Same as dynamic cast but always throw std::bad_cast
exception in case of failure
!   C++ dynamic cast returns null pointer in case of failed
conversion of a pointer and returns std::bad_cast in
case of failed conversion of a reference
Boost/cast.hpp
!   Numeric casts ensure that conversions between
numeric types (char, int , float, etc) are valid and legal
or they are not allowed
!   Usage:
char c=boost: : numeric_cast<char>(12) ;
float f=boost: : numeric_cast<float>( 3. 001) ;
Boost/lexical_cast.hpp
!   This handles conversions to and from string type ()
!   Usage:
std: : string s=" 42 ";
int i=boost: : lexical_cast<int>(s) ;
// float to string
float f=3 . 14151;
s=boost: : lexical_cast<std: : string>(f) ;
Library 3: Utility
!   Compile time assertions with BOOST_STATIC_ASSERT
!   Safe destruction with checked_delete and
checked_array_delete
!   Prohibition of copying with noncopyable
!   Retrieval of object addresses when operator& is overloaded
through addressof
!   Controlled participation of overloads and specializations
withenable_if and disable_if
Boost/static_assert.h
!   To enforce assertions during compile time
!   Usage:
#include <iostream>
#include " boost/type_traits. hpp“
#include " boost/static_assert. hpp“
template <typename T> class
only_compatible_with_integral_types {
BOOST_STATI C_ASSERT(boost: : is_integral<T>: :
value) ;} ;
Boost/checked_Delete.hpp
!   When deleting an object through a pointer, the result
is typically dependent on whether the type being
deleted is known at the time of the deletion. There are
hardly ever compiler warnings when deleting a pointer
to an incomplete type, but it can cause all kinds of
trouble, because the destructor may not be invoked.
This, in turn, means that cleanup code won’t be
performed. checked_delete is in effect a static assertion
that the class type is known upon destruction,
enforcing the constraint that the destructor will be
called.
Usage: checked delete
#include " boost/checked_delete. hpp“
class some_class;
some_class* create() {return (some_class*) 0;}
int main()
{
some_class* p2=create() ;
boost: : checked_delete(p2 ) ;
}
Noncopyable (boost/
utility.hpp)
!   It prohibits access to the copy construtor and assignment
operator of a class which derives from the class noncopyable
!   Usage:
#include " boost/utility. hpp“
class please_dont_make_copies : boost: : noncopyable { } ;
int main() {
please_dont_make_copies d1;
please_dont_make_copies d2(d1) ;
please_dont_make_copies d3;
d3=d1;
}
Boost::addressof (boost/
utility.hpp)
!  Used to get the address of objects (like the & operator)
!  Is useful when & operator Is overloaded
!  Usage:
#include " boost/utility. hpp“
class some_class { } ;
int main()
{
some_class s;
some_class* p=boost: : addressof(s) ;
}
boost/utility/enable_if. Hpp
enable_if/disable_if
!  Controls whether a certain
function or template
specialization can participate in
overload resolution process
Usage (enable_if):
#include <iostream>
#include " boost/utility/enable_if. hpp“
#include " boost/type_traits. hpp“
#include " boost/mpl/has_xxx.hpp“
BOOST_MPL_HAS_XXX_TRAIT_DEF(type);
void some_func( int i)
{
std: : cout << " void some_func(" << i << " ) n";
}
Usage(contd)
template <typename T> void some_func(T t,typename
boost: : enable_if<has_type<T> >: : type* p=0) {
typename T: : type variable_of_nested_type;
std: : cout << " template <typename T> void
some_func( T t) n" ;
}
Library IV: Regex (boost/
regex.hpp)
Usage:
boost: : regex reg( " (A. * ) ") ;
bool b=boost: : regex_match(" This expression could
match from A and beyond. ",reg) ;
Library V: Any (boost/
any.hpp)
Usage:
Boost::any a;
a=std::string(“A string”);
A=42;
A=3.1415;
Std:string S= boost::any_cast<std::string>(a);
//throws boost::bad_Any_cast
Library VI: Variant (boost/
variant.hpp)
Usage:
Boost::variant <int, std::string,double> my_first_variant(“Hello
World”);
My_first_variant = 2;
My_first_variant= 4.52;
My_first_variant= “Fabulous”;
My_first_variant = 0;
Assert(boost::get<int>(my_first_variant)==0);
Library VII: Tuple (boost/
tuple/tuple.hpp)
!   Allows grouping of values upto 10 elements as against 2
elements provided by STL
!   Usage:
boost: : tuple<int, double, std: : string>triple(42, 3 . 14,
" My first tuple! " ) ;
Library VIII: bind
Usage:
#include <iostream>
#include " boost/bind. hpp“
void nine_arguments(int i1, int i2 , int i3, int i4,int i5, int i6 , int i7, int i8,
int i9)
{
std: : cout << i1 << i2 << i3 << i4 << i5 < < i6 << i7 << i8 << i9 << ' n' ;
}
Usage (contd): Bind:
int main( ) {
int i1=1, i2=2, i3=3, i4=4, i5=5, i6=6, i7=7, i8=8, i9=9;
( boost: : bind( &nine_arguments, _9, _2, _1, _6, _3 , _8,
_4, _5, _7) )( i1, i2 , i3, i4, i5, i6, i7, i8, i9) ;
}
Library IX: Lambda
#include <iostream>
#include " boost/lambda/lambda. hpp“
#include " boost/function. hpp“
int main()
{
using namespace boost: : lambda;
( std: : cout << _1 << " " << _3 << " " << _2 << "! n")(" Hello", " friend" , " my" ) ;
boost: : function< void(int, int, int) > f=std: : cout << _1 << "* " << _2 << " +" << _3 << " ="
<<_1*_2 +_3 << " n" ;
f(1, 2, 3) ;
f(3, 2, 1) ;
}
Library X: Function
Usage:
#include <iostream>
#include " boost/function. hpp“
bool some_func(int i, double d)
{
return i>d;
}
int main( )
{
boost: : function<bool ( int, double) > f;
f=&some_func;
}
Library XI: Signals
Usage:
#include <iostream>
#include " boost/signals. hpp“
void my_first_slot( ) {
std: : cout << " void my_first_slot() n" ;
}
class my_second_slot {
public:void operator() () const {
std: : cout << " void my_second_slot: : operator() ( ) constn";
}
};
Signals (contd)
int main( ) {
boost: : signal<void () > sig;
sig. connect(&my_first_slot) ;
sig. connect(my_second_slot() ) ;
std: : cout << " Emitting a signal. . . n";sig() ;
}
Library XII: Boost MPL
(metaprogramming library)
!   The Boost.MPL library is a general-purpose, high-level
C++ template metaprogramming framework of
compile-time algorithms, sequences and metafunctions.
It provides a conceptual foundation and an extensive
set of powerful and coherent tools.
!   Visit:
http://www.boost.org/doc/libs/1_47_0/libs/mpl/
doc/index.html
Library XIII: BGL (Boost
Graph Library)
!   Part of the Boost Graph Library is a generic interface that
allows access to a graph's structure, but hides the details of
the implementation. This is an “open” interface in the sense
that any graph library that implements this interface will be
interoperable with the BGL generic algorithms and with
other algorithms that also use this interface. The BGL
provides some general purpose graph classes that conform to
this interface, but they are not meant to be the “only” graph
classes; there certainly will be other graph classes that are
better for certain situations.
!   Visit:
http://www.boost.org/doc/libs/1_47_0/libs/graph/doc/s
Section IV:
Multithreading
C++ Threads
!   Standard C++ contains no native support for
multithreading, so it is not possible towrite portable
multithreaded code the same way you would write portable
code thatuses other standard library classes like string,
vector, list, and so on. The BoostThreads library goes a long
way toward making a standard, portable multithreading
library though, and it is designed to minimize many
common multithreadingheadaches.
!   Visit:
http://www.boost.org/doc/libs/1_47_0/doc/html/
thread.html
Q & A

More Related Content

What's hot

Intro to C++ - language
Intro to C++ - languageIntro to C++ - language
Intro to C++ - language
Jussi Pohjolainen
 
C# for C++ Programmers
C# for C++ ProgrammersC# for C++ Programmers
C# for C++ Programmers
russellgmorley
 
basics of c++
basics of c++basics of c++
basics of c++
gourav kottawar
 
basics of C and c++ by eteaching
basics of C and c++ by eteachingbasics of C and c++ by eteaching
basics of C and c++ by eteaching
eteaching
 
Introduction Of C++
Introduction Of C++Introduction Of C++
Introduction Of C++
Sangharsh agarwal
 
Modern c++ (C++ 11/14)
Modern c++ (C++ 11/14)Modern c++ (C++ 11/14)
Modern c++ (C++ 11/14)
Geeks Anonymes
 
C introduction by thooyavan
C introduction by  thooyavanC introduction by  thooyavan
C introduction by thooyavan
Thooyavan Venkatachalam
 
Advanced Programming C++
Advanced Programming C++Advanced Programming C++
Advanced Programming C++
guestf0562b
 
C++ Programming
C++ ProgrammingC++ Programming
C++11
C++11C++11
Solid C++ by Example
Solid C++ by ExampleSolid C++ by Example
Solid C++ by Example
Olve Maudal
 
Oop l2
Oop l2Oop l2
C++ presentation
C++ presentationC++ presentation
C++ presentation
SudhanshuVijay3
 
Summary of C++17 features
Summary of C++17 featuresSummary of C++17 features
Summary of C++17 features
Bartlomiej Filipek
 
Introduction to cpp
Introduction to cppIntroduction to cpp
Introduction to cpp
Nilesh Dalvi
 
Oops presentation
Oops presentationOops presentation
Oops presentation
sushamaGavarskar1
 
C++11
C++11C++11
C++ Advanced
C++ AdvancedC++ Advanced
C++ Advanced
Vivek Das
 
C Programming Tutorial - www.infomtec.com
C Programming Tutorial - www.infomtec.comC Programming Tutorial - www.infomtec.com
C Programming Tutorial - www.infomtec.com
M-TEC Computer Education
 
Virtual function in C++ Pure Virtual Function
Virtual function in C++ Pure Virtual Function Virtual function in C++ Pure Virtual Function
Virtual function in C++ Pure Virtual Function
Kamlesh Makvana
 

What's hot (20)

Intro to C++ - language
Intro to C++ - languageIntro to C++ - language
Intro to C++ - language
 
C# for C++ Programmers
C# for C++ ProgrammersC# for C++ Programmers
C# for C++ Programmers
 
basics of c++
basics of c++basics of c++
basics of c++
 
basics of C and c++ by eteaching
basics of C and c++ by eteachingbasics of C and c++ by eteaching
basics of C and c++ by eteaching
 
Introduction Of C++
Introduction Of C++Introduction Of C++
Introduction Of C++
 
Modern c++ (C++ 11/14)
Modern c++ (C++ 11/14)Modern c++ (C++ 11/14)
Modern c++ (C++ 11/14)
 
C introduction by thooyavan
C introduction by  thooyavanC introduction by  thooyavan
C introduction by thooyavan
 
Advanced Programming C++
Advanced Programming C++Advanced Programming C++
Advanced Programming C++
 
C++ Programming
C++ ProgrammingC++ Programming
C++ Programming
 
C++11
C++11C++11
C++11
 
Solid C++ by Example
Solid C++ by ExampleSolid C++ by Example
Solid C++ by Example
 
Oop l2
Oop l2Oop l2
Oop l2
 
C++ presentation
C++ presentationC++ presentation
C++ presentation
 
Summary of C++17 features
Summary of C++17 featuresSummary of C++17 features
Summary of C++17 features
 
Introduction to cpp
Introduction to cppIntroduction to cpp
Introduction to cpp
 
Oops presentation
Oops presentationOops presentation
Oops presentation
 
C++11
C++11C++11
C++11
 
C++ Advanced
C++ AdvancedC++ Advanced
C++ Advanced
 
C Programming Tutorial - www.infomtec.com
C Programming Tutorial - www.infomtec.comC Programming Tutorial - www.infomtec.com
C Programming Tutorial - www.infomtec.com
 
Virtual function in C++ Pure Virtual Function
Virtual function in C++ Pure Virtual Function Virtual function in C++ Pure Virtual Function
Virtual function in C++ Pure Virtual Function
 

Similar to C++ Training

c# at f#
c# at f#c# at f#
c# at f#
Harry Balois
 
C# AND F#
C# AND F#C# AND F#
C# AND F#
Harry Balois
 
C++ Interview Questions
C++ Interview QuestionsC++ Interview Questions
C++ Interview Questions
Kaushik Raghupathi
 
SRAVANByCPP
SRAVANByCPPSRAVANByCPP
SRAVANByCPP
aptechsravan
 
C questions
C questionsC questions
C questions
parm112
 
New microsoft office word document (2)
New microsoft office word document (2)New microsoft office word document (2)
New microsoft office word document (2)
rashmita_mishra
 
Boo Manifesto
Boo ManifestoBoo Manifesto
Boo Manifesto
hu hans
 
Glimpses of C++0x
Glimpses of C++0xGlimpses of C++0x
Glimpses of C++0x
ppd1961
 
C language updated
C language updatedC language updated
C language updated
Arafat Bin Reza
 
Introduction to c_plus_plus (6)
Introduction to c_plus_plus (6)Introduction to c_plus_plus (6)
Introduction to c_plus_plus (6)
Sayed Ahmed
 
Introduction to c_plus_plus
Introduction to c_plus_plusIntroduction to c_plus_plus
Introduction to c_plus_plus
Sayed Ahmed
 
Effective c++notes
Effective c++notesEffective c++notes
Effective c++notes
Uttam Gandhi
 
Presentation 5th
Presentation 5thPresentation 5th
Presentation 5th
Connex
 
C#ppt
C#pptC#ppt
C,c++ interview q&a
C,c++ interview q&aC,c++ interview q&a
C,c++ interview q&a
Kumaran K
 
Cpp17 and Beyond
Cpp17 and BeyondCpp17 and Beyond
Cpp17 and Beyond
ComicSansMS
 
88 c-programs
88 c-programs88 c-programs
88 c-programs
Leandro Schenone
 
Oops lecture 1
Oops lecture 1Oops lecture 1
Oops lecture 1
rehan16091997
 
Gentle introduction to modern C++
Gentle introduction to modern C++Gentle introduction to modern C++
Gentle introduction to modern C++
Mihai Todor
 
C by balaguruswami - e.balagurusamy
C   by balaguruswami - e.balagurusamyC   by balaguruswami - e.balagurusamy
C by balaguruswami - e.balagurusamy
Srichandan Sobhanayak
 

Similar to C++ Training (20)

c# at f#
c# at f#c# at f#
c# at f#
 
C# AND F#
C# AND F#C# AND F#
C# AND F#
 
C++ Interview Questions
C++ Interview QuestionsC++ Interview Questions
C++ Interview Questions
 
SRAVANByCPP
SRAVANByCPPSRAVANByCPP
SRAVANByCPP
 
C questions
C questionsC questions
C questions
 
New microsoft office word document (2)
New microsoft office word document (2)New microsoft office word document (2)
New microsoft office word document (2)
 
Boo Manifesto
Boo ManifestoBoo Manifesto
Boo Manifesto
 
Glimpses of C++0x
Glimpses of C++0xGlimpses of C++0x
Glimpses of C++0x
 
C language updated
C language updatedC language updated
C language updated
 
Introduction to c_plus_plus (6)
Introduction to c_plus_plus (6)Introduction to c_plus_plus (6)
Introduction to c_plus_plus (6)
 
Introduction to c_plus_plus
Introduction to c_plus_plusIntroduction to c_plus_plus
Introduction to c_plus_plus
 
Effective c++notes
Effective c++notesEffective c++notes
Effective c++notes
 
Presentation 5th
Presentation 5thPresentation 5th
Presentation 5th
 
C#ppt
C#pptC#ppt
C#ppt
 
C,c++ interview q&a
C,c++ interview q&aC,c++ interview q&a
C,c++ interview q&a
 
Cpp17 and Beyond
Cpp17 and BeyondCpp17 and Beyond
Cpp17 and Beyond
 
88 c-programs
88 c-programs88 c-programs
88 c-programs
 
Oops lecture 1
Oops lecture 1Oops lecture 1
Oops lecture 1
 
Gentle introduction to modern C++
Gentle introduction to modern C++Gentle introduction to modern C++
Gentle introduction to modern C++
 
C by balaguruswami - e.balagurusamy
C   by balaguruswami - e.balagurusamyC   by balaguruswami - e.balagurusamy
C by balaguruswami - e.balagurusamy
 

Recently uploaded

basic-wireline-operations-course-mahmoud-f-radwan.pdf
basic-wireline-operations-course-mahmoud-f-radwan.pdfbasic-wireline-operations-course-mahmoud-f-radwan.pdf
basic-wireline-operations-course-mahmoud-f-radwan.pdf
NidhalKahouli2
 
Recycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part IIIRecycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part III
Aditya Rajan Patra
 
Engine Lubrication performance System.pdf
Engine Lubrication performance System.pdfEngine Lubrication performance System.pdf
Engine Lubrication performance System.pdf
mamamaam477
 
Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...
IJECEIAES
 
Casting-Defect-inSlab continuous casting.pdf
Casting-Defect-inSlab continuous casting.pdfCasting-Defect-inSlab continuous casting.pdf
Casting-Defect-inSlab continuous casting.pdf
zubairahmad848137
 
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming PipelinesHarnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
Christina Lin
 
Understanding Inductive Bias in Machine Learning
Understanding Inductive Bias in Machine LearningUnderstanding Inductive Bias in Machine Learning
Understanding Inductive Bias in Machine Learning
SUTEJAS
 
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressionsKuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
Victor Morales
 
Engineering Drawings Lecture Detail Drawings 2014.pdf
Engineering Drawings Lecture Detail Drawings 2014.pdfEngineering Drawings Lecture Detail Drawings 2014.pdf
Engineering Drawings Lecture Detail Drawings 2014.pdf
abbyasa1014
 
Iron and Steel Technology Roadmap - Towards more sustainable steelmaking.pdf
Iron and Steel Technology Roadmap - Towards more sustainable steelmaking.pdfIron and Steel Technology Roadmap - Towards more sustainable steelmaking.pdf
Iron and Steel Technology Roadmap - Towards more sustainable steelmaking.pdf
RadiNasr
 
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...Electric vehicle and photovoltaic advanced roles in enhancing the financial p...
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...
IJECEIAES
 
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
Yasser Mahgoub
 
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODELDEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
gerogepatton
 
官方认证美国密歇根州立大学毕业证学位证书原版一模一样
官方认证美国密歇根州立大学毕业证学位证书原版一模一样官方认证美国密歇根州立大学毕业证学位证书原版一模一样
官方认证美国密歇根州立大学毕业证学位证书原版一模一样
171ticu
 
22CYT12-Unit-V-E Waste and its Management.ppt
22CYT12-Unit-V-E Waste and its Management.ppt22CYT12-Unit-V-E Waste and its Management.ppt
22CYT12-Unit-V-E Waste and its Management.ppt
KrishnaveniKrishnara1
 
A SYSTEMATIC RISK ASSESSMENT APPROACH FOR SECURING THE SMART IRRIGATION SYSTEMS
A SYSTEMATIC RISK ASSESSMENT APPROACH FOR SECURING THE SMART IRRIGATION SYSTEMSA SYSTEMATIC RISK ASSESSMENT APPROACH FOR SECURING THE SMART IRRIGATION SYSTEMS
A SYSTEMATIC RISK ASSESSMENT APPROACH FOR SECURING THE SMART IRRIGATION SYSTEMS
IJNSA Journal
 
Properties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptxProperties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptx
MDSABBIROJJAMANPAYEL
 
ISPM 15 Heat Treated Wood Stamps and why your shipping must have one
ISPM 15 Heat Treated Wood Stamps and why your shipping must have oneISPM 15 Heat Treated Wood Stamps and why your shipping must have one
ISPM 15 Heat Treated Wood Stamps and why your shipping must have one
Las Vegas Warehouse
 
A review on techniques and modelling methodologies used for checking electrom...
A review on techniques and modelling methodologies used for checking electrom...A review on techniques and modelling methodologies used for checking electrom...
A review on techniques and modelling methodologies used for checking electrom...
nooriasukmaningtyas
 
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
IJECEIAES
 

Recently uploaded (20)

basic-wireline-operations-course-mahmoud-f-radwan.pdf
basic-wireline-operations-course-mahmoud-f-radwan.pdfbasic-wireline-operations-course-mahmoud-f-radwan.pdf
basic-wireline-operations-course-mahmoud-f-radwan.pdf
 
Recycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part IIIRecycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part III
 
Engine Lubrication performance System.pdf
Engine Lubrication performance System.pdfEngine Lubrication performance System.pdf
Engine Lubrication performance System.pdf
 
Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...
 
Casting-Defect-inSlab continuous casting.pdf
Casting-Defect-inSlab continuous casting.pdfCasting-Defect-inSlab continuous casting.pdf
Casting-Defect-inSlab continuous casting.pdf
 
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming PipelinesHarnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
 
Understanding Inductive Bias in Machine Learning
Understanding Inductive Bias in Machine LearningUnderstanding Inductive Bias in Machine Learning
Understanding Inductive Bias in Machine Learning
 
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressionsKuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
 
Engineering Drawings Lecture Detail Drawings 2014.pdf
Engineering Drawings Lecture Detail Drawings 2014.pdfEngineering Drawings Lecture Detail Drawings 2014.pdf
Engineering Drawings Lecture Detail Drawings 2014.pdf
 
Iron and Steel Technology Roadmap - Towards more sustainable steelmaking.pdf
Iron and Steel Technology Roadmap - Towards more sustainable steelmaking.pdfIron and Steel Technology Roadmap - Towards more sustainable steelmaking.pdf
Iron and Steel Technology Roadmap - Towards more sustainable steelmaking.pdf
 
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...Electric vehicle and photovoltaic advanced roles in enhancing the financial p...
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...
 
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
 
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODELDEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
 
官方认证美国密歇根州立大学毕业证学位证书原版一模一样
官方认证美国密歇根州立大学毕业证学位证书原版一模一样官方认证美国密歇根州立大学毕业证学位证书原版一模一样
官方认证美国密歇根州立大学毕业证学位证书原版一模一样
 
22CYT12-Unit-V-E Waste and its Management.ppt
22CYT12-Unit-V-E Waste and its Management.ppt22CYT12-Unit-V-E Waste and its Management.ppt
22CYT12-Unit-V-E Waste and its Management.ppt
 
A SYSTEMATIC RISK ASSESSMENT APPROACH FOR SECURING THE SMART IRRIGATION SYSTEMS
A SYSTEMATIC RISK ASSESSMENT APPROACH FOR SECURING THE SMART IRRIGATION SYSTEMSA SYSTEMATIC RISK ASSESSMENT APPROACH FOR SECURING THE SMART IRRIGATION SYSTEMS
A SYSTEMATIC RISK ASSESSMENT APPROACH FOR SECURING THE SMART IRRIGATION SYSTEMS
 
Properties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptxProperties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptx
 
ISPM 15 Heat Treated Wood Stamps and why your shipping must have one
ISPM 15 Heat Treated Wood Stamps and why your shipping must have oneISPM 15 Heat Treated Wood Stamps and why your shipping must have one
ISPM 15 Heat Treated Wood Stamps and why your shipping must have one
 
A review on techniques and modelling methodologies used for checking electrom...
A review on techniques and modelling methodologies used for checking electrom...A review on techniques and modelling methodologies used for checking electrom...
A review on techniques and modelling methodologies used for checking electrom...
 
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
 

C++ Training

  • 1. Exploring C++ Presenter:- Subhendra Basu (SysTools Team)
  • 2. Background Check !   Familiarity with basic imperative programming concepts !   Variables (scoping, global/local) !   Loops !   Functions and function abstraction !   Prior experience with OOP and knowledge of basic OOP concepts (inheritance, overloading, etc.)
  • 3. Session Outline** !   A brief overview of basic C++ concepts !   Overview of STL !   Overview of Boost !   Templates !   Exception Handling !   Best Practices !   Design Patterns !   Web Programming ! gcov and cppunit !   Questions and References **This Talk is not meant to be a exhaustive reference to C++ but just an overview of the Basics
  • 4. Which Programming Language is the fastest ? http://shootout.alioth.debian.org/u32q/which-programming-languages-are-fastest.php
  • 5. Binary Code Assembly Languages Procedural Languages (C, Fortran, COBOL…) OO Languages ( C++, Java, Python…) Declarative languages (Haskell, ML, Prolog…) ? Towards a higher level of abstraction
  • 6. Current Status of C++ !   Current day C++ cannot be regarded as “the language C with classes” !   C++ is a federation of languages that supports !   Procedural !   Object Oriented !   Functional !   Generic ! Metaprogramming features
  • 7. Primary Programming Paradigms in C++ !   C : Blocks, Statements, Preprocessor, Built-in Data Types, Arrays, Pointers !   Object Oriented C++ : classes, encapsulation, inheritance, polymorphism, virtual functions (dynamic binding) !   Template C++ : Generic Programming part of C++ (also known as Template Metaprogramming) !   The Standard Template Library Caution: Rules for Effective C++ Programming vary depending on the part of C++ you are using
  • 8. Section I: C++ Basics through Best Practices
  • 9. {Const, Enum, Inline} vs #define !   Prefer the compiler to the preprocessor !   Defining a constant or a macro through a hash define is risky. Compiler errors may point to the value of the constant and not the variable used to define the constant making debugging difficult. Instead use ‘const’ or ‘enum’ !   Macros can be rewritten as inline function to avoid side-effects
  • 10. The ‘enum’ hack Consider the code: Class GamePlayer { private: static const int NumTurns = 5; enum { NumTurns = 5 }; int scores[NumTurns]; … }
  • 11. Move over C macros // call f with maximum of a and b #define CALL_WITH_MAX(a,b) f((a) > (b) ? (a):(b)) int a=5; b=0; CALL_WITH_MAX(++a, b); //a is incremented twice CALL_WITH_MAX(++a, b+10); //a is incremented once Better way: template <typename T> inline void callWithMax(const T& a, const T& b){ f(a>b?a:b); }
  • 12. Pointers vs References Pointers !   Can be null !   May not be initialized at the point of definition !   Can be assigned to different objects at different points of time. References !   Nothing called as a “null” reference. Always points to an object !   It is compulsory to initialize a reference when defining it !   The object it points to cannot be changed on the fly. It keeps pointing to the value it was initialized with. !   More efficient to use than pointers as there need not be any run-time type checking to validate whether it is null or not
  • 13. Prefer C++ style casts !   Easier to parse for humans and tools !   Allows compilers to catch casting errors which otherwise would go undetected !   Four types of casting are supported: ! static_cast ! const_cast ! reinterpret_cast ! dynamic_cast
  • 14. Use const whenever possible !   Declaring something ‘const’ helps compilers detect usage errors. const can be applied to objects at any scope, to function parameters and return types, and to member functions as a whole. !   Compilers enforce bitwise or physical constness, but you should program using logical or conceptual constness !   When const and non-cost member functions have essentially identical implementation, code duplication can be avoided by having the non-const version call the const version
  • 15. Make sure objects are initialized before they are used !   Reading uninitialized values yields undefined behavior !   Manually initialize objects of built-in type, because C++ only sometimes initializes them itself. !   In a constructor, prefer use of the member initialization list to assignment inside the body of the constructor. List data members in the initialization list in the same order they’re declared in a class. !   Avoid initialization order problems across translation units by replacing non-local static objects with local static objects
  • 16. Never treat Arrays Polymorphically !   The result of deleting an array of derived class objects through a base class pointer is undefined. !   Polymorphism and pointer arithmetic don’t mix
  • 17. Classes !   A class is like a cookie cutter; it defines the shape of the objects !   Objects are like cookies; they are instances of the class
  • 18. What C++ silently writes and calls !   Defining an empty class incites the compiler to declare its own versions of copy constructor, copy assignment operator, and a destructor and also a default constructor. All these functions will be both public and inline. !   These functions are generated only if they are needed !   E.g. class Empty {}; Empty e1; //default constructor //destructor Empty e2(e1); //copy constructor E2=e1; copy assignment operator
  • 19. Explicitly disallow the use of compiler-generated functions you do not want !   Declare the functions (Copy constructor/assignment operator) but declare them private. !   But member and friend functions still have access to this !   So declare them but don’t define them. (gives a link time error when called) !   Possible to move the link time error to compile time. !   Privately Inherit from a class that is uncopyable. (‘noncopyable’ in Boost in boost/utility.hpp)
  • 20. 1. Declare destructors virtual in polymorphic base classes 2. Avoid default constructors where they are not needed 3. Prevent exceptions from leaving destructors 4. Never call virtual functions during construction or destruction 5. Have assignment operators return a reference to *this 6. Handle assignment to self in operator= 7. Copy all parts of an object Miscellaneous best practices in C++
  • 21. Inheriatance and Access to Base Classes Class X: public B { /**/} Class Y: protected B { /**/} Class Z: private B { /**/}
  • 22. !   When B is a public base, its public members can be used by any function. Its protected members can be used by members and friends of D and members and friends of classes derived from D. Any function can convert a D* to a B* !   When B is a protected base, its public and protected members can be used only by member functions and friends of classes derived from D and by member functions and friends of classes derived from D. Only friends and members of D and friends and members of classes derived from D can convert D* to B* !   When B is a private base, its public and protected members can be used only by member functions and friends of D. Only friends and members of D can convert D* to B*
  • 23. Memory Management : auto_ptr !   Prevent memory leaks by using auto_ptr (smart pointer) whose destructor calls delete on what it points to. std::auto_ptr<Investment>pInv(createInvestment()); o  There should not be more than one auto_ptr pointing to an object as this would lead to multiple deletion and undefined behavior o  auto_ptrs have the property that if they are copied using copy constructor or copy assignment operator, this sets them to null and the copying pointer assumes sole ownership of the resource
  • 24. auto_ptr copying example std::auto_ptr<Investment> pInv1(createInvestment()); // pInv1 points to the object returned from createInvestment std::auto_ptr<Investment> pInv2(pInv1); //pInv2 points to the object, pInv1is null pInv1 = pInv2;
  • 25. Memory Management: shared_ptr !   A reference counting smart pointer (RCSP) keeps track of how many objects point to a particular resource and automatically deletes the resource when nobody is pointing to it any longer. RCSPs offer behavior similar to garbage collection. !   TR1’s shared::ptr and boost::shared_ptr are examples of RCSPs !   Both auto_ptr and tr1::shared_ptr use delete in their destructors, not delete[] so cannot be used with dynamically allocated arrays. !   However Boost has boost::scoped_array and Boost::shared_array have the required behavior
  • 26. Section II : Template Metaprogramming
  • 27. What are templates and why Templates ? !   Templates are functions or classes written for one or more types not yet specified !   Extensive Application, the C++ STL library makes heavy use of templates !   It is usually a good idea to debug a particular class, such as String, before turning it into a template String<C>. This is done for ease of debugging
  • 28. Template Instantiation !   The process of generating a class declaration from a template class and a template argument is called template instantiation !   A version of a template for a particular template argument is called a specialization !   Templates provide a powerful way of generating code from relatively short definitions. So it has to be used with caution lest the memory will be flooded by almost identical function definitions
  • 29. Function Templates !   Function templates are essential for writing generic algorithms to be applied to a wide variety of container types. The ability to deduce the template arguments for a call from the function arguments is crucial. !   However class template parameters are never deduced. This is because the flexibility provided by several constructors for a class make such a deduction impossible in many cases and obscure in many more. !   Example: template <class T> void sort(vector<T>& v) { //… }
  • 30. Function Template overloading !   It is possible to declare several function templates with the same name and even declare a combination of function templates and ordinary functions with the same name. !   Example: template<class T> T sqrt(T); template<class T> complex<T> sqrt(complex<T>); double sqrt(double); void f(complex<double> z) { sqrt(2); //sqrt<int> (int) sqrt(2.0); //sqrt(double) sqrt(z); //sqrt<double>(complex<double>) }
  • 31. Using template arguments to specify policy !   Consider string sorting program. Three concepts are involved: string, element type and the comparison “policy”. !   Take for example, sorting swedish names: template<class T, class C> int compare(const String<T>& str1, const String<T>& str2) { for (int i=0; i<str1.length() && i<str2.length(); i++) { if (!C::eq(str1[i], str2[i])) return C::lt(str1[i],str2[i])? -1:1; return str1.length()-str2.length(); }
  • 32. Sorting Policy (contd) The Comparison Policy: template<class T> class Cmp { public: static int eq(T a, T b) {return a==b;} static int lt(T a, T b) { return a<b;} }; class Literate { public: static int eq(char a, char b) {return a==b;} static int lt(char, char); //table lookup based on character value }; Void f(String<char> swede1, String<char> swede2) { compare<char, Cmp<char> (swede1, swede2); compare(char, Literate>(swede1, swede2); }
  • 33. Default Template Parameters template<class T, class C = Cmp<T> > Int compare(const String<T>& str1, const String<T>& str2) { //… } Void f(String<char> swede1, String<char> swede2) { Compare(swede1, swede2); //use Cmp<char> }
  • 34. Template Specialization !   By default, a template gives a single definition to be used for every template argument that is possible. !   In template specialization, an alternative definition is provided for a type supplied by the user. This increases run-time efficiency by avoiding code bloat and maximizing the amount of shared code
  • 35. Complete Specialization Template<> class Vector <void*> { void** p; // void*& operator[](int i); }
  • 36. Partial Specialization Template<class T>class Vector<T*>: private Vector<void*>{ }; Vector<Shape*> vps; //T= Shape Vector<int**> vppi; // T=int*
  • 37. Order of Specialization Template<class T>class Vector; //general Template<class T>class Vector<T*>; specialized for any pointer Template<> class Vector<void*>; //specialized for void*
  • 39. Exceptions !   An exception is an object of some class representing an exceptional occurrence. !   Code that detects an error “throws” an object !   A piece of code expresses its desire to handle exception by a catch clause. !   The effect of a “throw” is to unwind the stack until a suitable “catch” is found
  • 40. Catching Exceptions Void f() { try { throw E(); } catch(H) { } }
  • 41. Catching Exceptions (conditions) The handler is invoked: 1.  If H is the same type as E 2.  If H is an unambiguous base of E 3.  If H and E are pointer types and [1] or [2] holds for the types to which they refer 4.  If H is a reference and [1] or [2] holds for the type to which H refers
  • 42. Re-Throw Void h() { try { //code that might throw Math Errors } catch(Matherr) { if (can handle_it_completely) { // handle the Matherr return; } else { throw; //rethrow the exception } } }
  • 43. Catch Every Exception void m() { try { } catch(…) { throw; }
  • 45. STL Basics !   STL stands for Standard Template Library. STL is the invention of Dave Musser, Alex Stepanov and Meng Lee. !   The main components of STL are: Containers, Iterators and Algorithms !   Containers are used to manage objects of a certain kind. Iterators are used to step through the containers. Algorithms are used to process the above collections of objects
  • 47. Containers !   There are two kinds of containers: !   Sequence Containers: These are ordered collections where each element has a certain position. STL has three predefined sequence containers: dequeue, vector and list !   Associative Containers: These are sorted collections in which the position of the element depends on its value due to a certain sorting criterion. STL ahs four predefined container classes: set, multiset, map, multimap
  • 48. Iterator iterating over elements of a list Begin() End() Pos++
  • 49. Set with six elements 4 2 6 1 3 5
  • 51. Library I: smart_ptr !   Automatic lifetime management of objects with shared_ptr makes shared ownership of resources effective and safe !   Safe observation of shared resources through weak_ptr avoids dangling pointers !   Scoped resources using scoped_ptr and scoped_array make the code easier to write and maintain, helps in writing exception free code
  • 52. Boost/scoped_ptr.hpp !   Boost::Scoped_ptr is used to ensure the proper deletion of a dynamically allocated object. ! Scoped_ptr is similar to auto_ptr but it doesn’t transfer ownership as auto_ptr does !   A scoped ptr cannot be copied or assigned at all Caution: Never ever store auto_ptr in standard library containers. Usually you get compiler error. If not, then you are in trouble.
  • 53. Scoped_ptr = const auto_ptr ? !  The difference is that a scoped pointer can be reset, effectively deleting and replacing the pointee when needed
  • 54. Boost/scoped_array.hpp !  Scoped arrays do for arrays what scoped_ptr do for pointers to single objects
  • 55. Boost/shared_ptr.hpp !   It is a reference counted smart pointer that eliminates the need to write complicated logic to control the lifetime of objects shared among two or more objects. !   RCSPs can be categorized as “intrusive” and “non- intrusive”. The former expects the classes which it manages to provide certain functionality to manage the reference count
  • 56. Boost/shared_array.hpp ! Shared_arrays is a smart pointer that enables shared ownership of arrays
  • 57. Library II: Conversion !   Understandable, maintainable and consistent polymorphic conversions !   Static downcasting using safer constructs than static_cast !   Range preserving numeric conversions that ensure correct value logic and less time debugging !   Correct and reusable lexical conversions that lead to less time coding
  • 58. Polymorphic_cast !   Same as dynamic cast but always throw std::bad_cast exception in case of failure !   C++ dynamic cast returns null pointer in case of failed conversion of a pointer and returns std::bad_cast in case of failed conversion of a reference
  • 59. Boost/cast.hpp !   Numeric casts ensure that conversions between numeric types (char, int , float, etc) are valid and legal or they are not allowed !   Usage: char c=boost: : numeric_cast<char>(12) ; float f=boost: : numeric_cast<float>( 3. 001) ;
  • 60. Boost/lexical_cast.hpp !   This handles conversions to and from string type () !   Usage: std: : string s=" 42 "; int i=boost: : lexical_cast<int>(s) ; // float to string float f=3 . 14151; s=boost: : lexical_cast<std: : string>(f) ;
  • 61. Library 3: Utility !   Compile time assertions with BOOST_STATIC_ASSERT !   Safe destruction with checked_delete and checked_array_delete !   Prohibition of copying with noncopyable !   Retrieval of object addresses when operator& is overloaded through addressof !   Controlled participation of overloads and specializations withenable_if and disable_if
  • 62. Boost/static_assert.h !   To enforce assertions during compile time !   Usage: #include <iostream> #include " boost/type_traits. hpp“ #include " boost/static_assert. hpp“ template <typename T> class only_compatible_with_integral_types { BOOST_STATI C_ASSERT(boost: : is_integral<T>: : value) ;} ;
  • 63. Boost/checked_Delete.hpp !   When deleting an object through a pointer, the result is typically dependent on whether the type being deleted is known at the time of the deletion. There are hardly ever compiler warnings when deleting a pointer to an incomplete type, but it can cause all kinds of trouble, because the destructor may not be invoked. This, in turn, means that cleanup code won’t be performed. checked_delete is in effect a static assertion that the class type is known upon destruction, enforcing the constraint that the destructor will be called.
  • 64. Usage: checked delete #include " boost/checked_delete. hpp“ class some_class; some_class* create() {return (some_class*) 0;} int main() { some_class* p2=create() ; boost: : checked_delete(p2 ) ; }
  • 65. Noncopyable (boost/ utility.hpp) !   It prohibits access to the copy construtor and assignment operator of a class which derives from the class noncopyable !   Usage: #include " boost/utility. hpp“ class please_dont_make_copies : boost: : noncopyable { } ; int main() { please_dont_make_copies d1; please_dont_make_copies d2(d1) ; please_dont_make_copies d3; d3=d1; }
  • 66. Boost::addressof (boost/ utility.hpp) !  Used to get the address of objects (like the & operator) !  Is useful when & operator Is overloaded !  Usage: #include " boost/utility. hpp“ class some_class { } ; int main() { some_class s; some_class* p=boost: : addressof(s) ; }
  • 67. boost/utility/enable_if. Hpp enable_if/disable_if !  Controls whether a certain function or template specialization can participate in overload resolution process
  • 68. Usage (enable_if): #include <iostream> #include " boost/utility/enable_if. hpp“ #include " boost/type_traits. hpp“ #include " boost/mpl/has_xxx.hpp“ BOOST_MPL_HAS_XXX_TRAIT_DEF(type); void some_func( int i) { std: : cout << " void some_func(" << i << " ) n"; }
  • 69. Usage(contd) template <typename T> void some_func(T t,typename boost: : enable_if<has_type<T> >: : type* p=0) { typename T: : type variable_of_nested_type; std: : cout << " template <typename T> void some_func( T t) n" ; }
  • 70. Library IV: Regex (boost/ regex.hpp) Usage: boost: : regex reg( " (A. * ) ") ; bool b=boost: : regex_match(" This expression could match from A and beyond. ",reg) ;
  • 71. Library V: Any (boost/ any.hpp) Usage: Boost::any a; a=std::string(“A string”); A=42; A=3.1415; Std:string S= boost::any_cast<std::string>(a); //throws boost::bad_Any_cast
  • 72. Library VI: Variant (boost/ variant.hpp) Usage: Boost::variant <int, std::string,double> my_first_variant(“Hello World”); My_first_variant = 2; My_first_variant= 4.52; My_first_variant= “Fabulous”; My_first_variant = 0; Assert(boost::get<int>(my_first_variant)==0);
  • 73. Library VII: Tuple (boost/ tuple/tuple.hpp) !   Allows grouping of values upto 10 elements as against 2 elements provided by STL !   Usage: boost: : tuple<int, double, std: : string>triple(42, 3 . 14, " My first tuple! " ) ;
  • 74. Library VIII: bind Usage: #include <iostream> #include " boost/bind. hpp“ void nine_arguments(int i1, int i2 , int i3, int i4,int i5, int i6 , int i7, int i8, int i9) { std: : cout << i1 << i2 << i3 << i4 << i5 < < i6 << i7 << i8 << i9 << ' n' ; }
  • 75. Usage (contd): Bind: int main( ) { int i1=1, i2=2, i3=3, i4=4, i5=5, i6=6, i7=7, i8=8, i9=9; ( boost: : bind( &nine_arguments, _9, _2, _1, _6, _3 , _8, _4, _5, _7) )( i1, i2 , i3, i4, i5, i6, i7, i8, i9) ; }
  • 76. Library IX: Lambda #include <iostream> #include " boost/lambda/lambda. hpp“ #include " boost/function. hpp“ int main() { using namespace boost: : lambda; ( std: : cout << _1 << " " << _3 << " " << _2 << "! n")(" Hello", " friend" , " my" ) ; boost: : function< void(int, int, int) > f=std: : cout << _1 << "* " << _2 << " +" << _3 << " =" <<_1*_2 +_3 << " n" ; f(1, 2, 3) ; f(3, 2, 1) ; }
  • 77. Library X: Function Usage: #include <iostream> #include " boost/function. hpp“ bool some_func(int i, double d) { return i>d; } int main( ) { boost: : function<bool ( int, double) > f; f=&some_func; }
  • 78. Library XI: Signals Usage: #include <iostream> #include " boost/signals. hpp“ void my_first_slot( ) { std: : cout << " void my_first_slot() n" ; } class my_second_slot { public:void operator() () const { std: : cout << " void my_second_slot: : operator() ( ) constn"; } };
  • 79. Signals (contd) int main( ) { boost: : signal<void () > sig; sig. connect(&my_first_slot) ; sig. connect(my_second_slot() ) ; std: : cout << " Emitting a signal. . . n";sig() ; }
  • 80. Library XII: Boost MPL (metaprogramming library) !   The Boost.MPL library is a general-purpose, high-level C++ template metaprogramming framework of compile-time algorithms, sequences and metafunctions. It provides a conceptual foundation and an extensive set of powerful and coherent tools. !   Visit: http://www.boost.org/doc/libs/1_47_0/libs/mpl/ doc/index.html
  • 81. Library XIII: BGL (Boost Graph Library) !   Part of the Boost Graph Library is a generic interface that allows access to a graph's structure, but hides the details of the implementation. This is an “open” interface in the sense that any graph library that implements this interface will be interoperable with the BGL generic algorithms and with other algorithms that also use this interface. The BGL provides some general purpose graph classes that conform to this interface, but they are not meant to be the “only” graph classes; there certainly will be other graph classes that are better for certain situations. !   Visit: http://www.boost.org/doc/libs/1_47_0/libs/graph/doc/s
  • 83. C++ Threads !   Standard C++ contains no native support for multithreading, so it is not possible towrite portable multithreaded code the same way you would write portable code thatuses other standard library classes like string, vector, list, and so on. The BoostThreads library goes a long way toward making a standard, portable multithreading library though, and it is designed to minimize many common multithreadingheadaches. !   Visit: http://www.boost.org/doc/libs/1_47_0/doc/html/ thread.html
  • 84. Q & A