Vous êtes sur la page 1sur 123

C++

Preliminaries

C++ fundamentals

   

C++ features
Modular with Object Oriented implementation ability; Robust - Strict type checking with variables and functions; Stream based Input/Output; Polymorphism supports function and operator polymorphism; Runtime memory management made easy with use of operators rather than with functions . Portable on operating systems

a. Program construct  Structure of a C++ program.  Preprocessor directives include, define, macros.  Comments single line and multi-line b. Data types
Sl.No Data type Default Values 1 2 3 4 5 6 7 8 int char float double bool structure pointer class Garbage Null Garbage Garbage Memory Requirements 2 1 4 8 1 Addressing type -

C++ Basics

Input and Output statements C ++ offers I-O objects, which are combined with stream operators to form statements. (i) Input : cin Syntax : cin >> var ; cin >> var1 >> var2 ; (ii) Output : cout Syntax : cout << msg string << vars ; cout << msg string << var1 << var2 ;


contd..

Note - Type specifiers and address operator are not needed.


  

Variables rules to declare variables; declarations at the point of use. Expressions arithmetic, relational, logical, bitwise. Type conversions automatic and type-casting

Logical Program layout


#include<iostream.h> void fun(); int x = 25; int main() { int a; char b; cin >>a >>b; fun(); cout<<a <<b<<x; } void fun() { cout <<Welcome to c++; }

Program Structure
main() {

Physical program layout

} fun() { }

Architecture of C++


Compilation Sequence Memory Structures Program Counter Stack Heap

   

Operators in C++
Sl.No Category 1 2 3 4 5 6 7 8 9 10 11 12 13 Ternary Binary Unary Operator Increment Decrement Minus Address Indirection Reference sizeof() Arithmetic Relational Bitwise Logical Assignment Symbol ++ -& * & sizeof() %, /, *, +, >,<,>=,<=,==,!= &, |, ~, >>,<<. &&, ||, ! = ?: L to R L to R L to R L to R R to L L to R Associativity L to R L to R L to R L to R L to R

contd..
Sl.No Category 14 15 16 17 Stream 18 19 20 21 Class Operator Dot Scope Resolution Arrow Insertion Extraction Memory new Allocation delete RTTI typeid() Symbol . :: -> << >> L to R L to R Associativity L to R L to R L to R

contd..
c. Control statements and Loops  Conditional statements (i) if (ii) ifelse (iii) elseif and (iv) switch.  Loops (i) while (ii) do...while (iii) for
Note : Nesting is permitted in conditional and looping statements.


break, continue, goto.

d. Constants Constants are declared using the keyword const.

contd..
e. Block orientation  C++ is a block oriented language ;  local variables get preference over the variables declared in upper scope.  for and do..while loops are treated as independent blocks.  bailout a concept wherein the variables are declared in the localized scope. void main() { int i=0; .. cout << &i; for(int i=0; i<5; i++) { . cout<< &i ; } cout<< &i; }

contd..
f. Reference variables  Reference variables are alias names for a given variable.  References are just another name for a given variable.  Reference operator - &  References provide power of pointer and flexibility of ordinary variables.  Applied in programming of copy constructors, operator overloading etc.

contd..
g. Functions  Functions provide for implementing modularity.  C++ functions implement strict type checking.  C++ provides for default arguments.  C++ implements function polymorphism.  Inline functions A function in C++ is treated as macro, when the keyword inline precedes its definition.  Reference Arguments A mechanism wherein, a reference to the original variable in the calling program is passed. Using references, the called function can access the actual variables in the calling function.

contd..
h. Storage classes  C++ supports four storage classes auto, static, register and extern; i. User defined data-types C++ uses the keyword typedef for user to define custom data types. j. Structures (i) definition ; (ii) structures contain both data and functions ; (iii) structure members have access specifiers; (iv) structures can be nested. (v) C++ provides for references to structures. Note: Structure template automatically becomes data type.

contd..
k. Pointers  Pointers are a data type of their own and also the data type of the data they are pointing to.  Single pointer is an array variable.  Pointer are made to point to array, string, structures. Pointers can be structure members. C++ supports self-referential structures.  Pointers can be made to point to constants and C++ provides for constant pointers also.  Pointers are used for dynamic memory allocation with operators new and delete.  Pointers can be function arguments and return types.  Pointers to functions are called as function pointers.

Object Oriented Programming

Object Oriented Programming


The OOP paradigm includes the following  Data Encapsulation;  Data Abstraction;  Polymorphism;  Inheritance;  Persistence  Delegation  Genericity

Classes and Objects


Class concept and definition  Syntax : class template { access specifier : data type var1; data type var2; access specifier : data type var3; data type var4; access specifier : func1() {} access specifier : func2() {} };  C++ has three access specifiers viz.. public, private, protected.

contd..
 Access specifiers

(i) public A class member with PUBLIC access specifier can be accessed by other class members, inherited classes and outside the class i.e. with objects. (ii) private A class member with PRIVATE access specifier can be accessed by other class members only. Private members cannot be inherited. (iii) protected A class member with PROTECTED access specifier can be accessed by other class members and inherited classes only. They cannot be accessed outside the classes by objects.

contd..


Class members  The class members are data and functions.  The data members are variables belonging to basic and derived data types viz.. array, structure and another class.  Functions contain the code which operates on the class data. Functions can be declared inside the class, or outside the class using scope resolution operator.  Objects  Objects are variables of the said class type.  Objects have direct access to public class members and indirect access to private and protected class members.  Objects can be initialized, manipulated upon, referenced upon and used as function arguments.

contd..
Constructors and Destructors (i) Constructor is a function which initializes the data members of the class.  A function is recognized as constructor if it has the same name as that of class template.  Constructor is invoked when an object is declared.  Constructors can be default, parameterized, overloaded. (ii) Destructor is a function which clears the memory allocated using constructors. A function is recognized as destructor if it is having the same name as class template preceded by the symbol ~ , tilde.  An object can be assigned/copied to another object.


 

Types of object copying are Shallow copy - In case of shallow copy, there is a member wise copy from source object into the destination object value wise. Deep copy The Deep copy, copies all fields and also makes copies of dynamically allocated memory pointed to by fields. Deep copy is done whenever an object has pointers to  dynamically allocated memory, and  the DMA needs to be copied when the original object is copied. Copy constructor is used to make deep copy and overload the assignment operator.

contd..

contd..
 

A Copy constructor is a special type of constructor invoked whenever a new object is created from an existing object. Its invoked in the following circumstances. o A variable is declared which is initialized from another object. o A value parameter is initialized from its corresponding argument. o An object is returned by a function. In each of the above cases, if the copy constructor does not exist, the system calls the default copy constructor.

contd..
V. Friend Functions

contd..


Empty Class

Operator Overloading

Operator Overloading
Concept of Operator overloading.  Implicit overloading in C and C++ - operators performing same operations on different data types.  Explicit overloading in C++ - operators performing the operations on user-defined data types.  The concept of operator overloading can also be applied to data conversions.  Overloading extends the semantics of an operator without changing its syntax.  The grammatical rules that govern its use such as number of operands, precedence and associativity remain the same for overloaded operators.

contd..


C++ overloadable operators


Operator Category Arithmetic Bitwise Logical Relational Assignment, Compound assignment Shift Unary Function call Dereferencing Unary sign prefix Allocate and Free 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11.

Sl.No.

contd..


Unary operator overloading : o returntype operator symbol() { . } Binary operator overloading : o returntype operator symbol(arg) { }

contd..


Data Conversion is of two types  Basic type to user-defined type : The conversion function is defined in the user defined objects class in the form of constructor. constructor-function (basic type) { steps for converting }  User defined type to basic type : The conversion function should be defined in user defined objects class in the form of operator function. operator basic-type( ) { steps for converting }

contd..


Conversion between objects of different classes Assign object of one class type to another class type class A class B A oba; { . { B obb; } ; } ; obb = oba; The conversion routine is set into the source object. class B { private : . public: operator classA( ) { } };

contd..


Alternatively, the conversion routine can also be defined in the destination objects class. Its defined as one-argument constructor. class A { private : public : class A(B obb) {. Pgm to convert obb to oba .} };

contd..
 

 

Overloading with Friend Functions : Its possible to overload operator function to be declared as Friend functions. In this case it is necessary to pass explicitly the arguments which otherwise are passed implicitly using operator functions. The concept mainly applied to overload stream operators. Gen Syntax : friend return-type operator symbol (arg1, arg2]) { // function body }

contd..


The following operators cannot be overloaded.  Member access - .  Scope resolution - ::  Conditional - ? :  Pointer to member - *  Sizeof sizeof(datatype). Operators that cannot be overloaded as friend operators  Assignment =  Function call ( )  Subscripting [ ]  Class member access ->

Inheritance

Inheritance
A process of creating new class from existing class(es).  The new class is called as Derived class , inherits all capabilities of the base class and can also add refinements of its own.  The class which provides for inheritance is called as Base class and is unchanged by the process.  Inheritance permits code reusability.  Inheritance helps in original conceptualization of a programming problem, and in overall design of the program.

Inheritance process class base { access specifier : data member ; access specifier : function member ; }; class derived : public/private derived class { access specifier : data member ; access specifier : function member ; };

contd..

contd..
Public / Private inheritance a way to declare derived classes.  public specifies that objects of the derived class are able to access public members of the base class.  private specifies that objects of the derived class cannot access public member functions of the base class. Note : Objects can never access private or protected members of a class.


Inheritance types C++ supports following types of inheritance.  Simple One base class and one derived class  Multilevel One base class, one derived class and another derived class from the previous derived class.  Hierarchical One base class and more than one derived classes.  Multiple More than one base classes and one derived class.  Hybrid Combination of different types of inheritances.

contd..

contd..


Constructors and Destructors in Inheritance

contd..
Multiple Inheritance - More than one base classes and one derived class. Syntax : class A { }; class B { }; class C : public A, public B { };


Inheriting an Empty class

contd..

contd..
Function Overriding  Member functions in a derived class can have the same signature as that in the base class.  When same function exists in both the base class and the derived class, the function in the derived class will be executed.  The derived class function is said to be overriding the base class function.


contd..


Polymorphism in Inheritance

contd..


Abstract base class the class used only for deriving other classes from it. This class is not instantiated.

C++ Streams

C ++ Streams
  

A program undergoes the process of input-computation-output. IO model of C++ model is based on concept of streams. C++ streams are categorized into input and output.
 

input keyboard, hdd output monitor, printer, hdd. support operator overloading provide a mechanism for filtering.

C++ streams
 

Note : The operators << and >> do not know about data types. They are overloaded into user defined data items.  C++ provides streams library - collection of objects and classes to handle, modify and extend any data type.

contd..


Console streams : There are three standard streams  cin standard input; keyboard  cout standard output; screen  cerr standard error output. The C++ streams make easy the job of the programmer by not making him to specify the data type.  cin is object of class istream_with_assign derived from class istream.  cout is object of class ostream_with_assign derived from class ostream.  >> is an extraction operator used to get data from stream  << is an insertion operator used to insert data into the stream.

Hierarchy of Stream classes


ios

istream

streambuf

ostream

iostream

istream_with assign

iostream_ with assign

ostream_ withassign

Stream classes
ios class provides operations common to both input and output. Contains a pointer to buffer object, constants and member functions which handle formatted i/o. istream class derived class of ios and hence inherits the properties of ios. Defines functions get(), getline(), and read(). Contains overloaded stream extraction operator >>. ostream class derived class of ios. Defines functions- put(), write(). Contains overloaded stream insertion operator <<.

contd..
 

iostream class derived from multiple base classes. Provides facility to handle both input and output. Classes istream_withassign, ostream_withassign, and iostream_withassign add assignment operators to their parent classes. The entire I/O functionality is centered around  Unformatted I/O operations  Formatted I/O operations  Manipulators

contd..


o o o


o o o

Unformatted I/O operations : cin and cout- most common i-o objects, defined in iostream.h. They support i/o of various data types. put() and get()- used to write and read single character. Member of ostream and istream respectively. getline() and write()- they are line oriented i/o functions. Formatted Console I/O operations : width() specifies required number of columns to be used while displaying the output. precision() specifies the number of digits to be displayed after decimal point. fill()- specifies a character to be used to fill unused area of field. By default fills blanks.

contd..
o setf() sets the format flag that controls the format of display(). o unsetf() clears the specified flag.  Manipulators o Manipulators are special functions used with >> or << to alter the behavior of any stream class instances. o Manipulators modify the working of the stream. o C++ has following manipulators 1. dec sets conversion to base 10. 2. hex sets conversion to base 16. 3. oct - sets conversion to base 8. 4. endl - outputs to new linw and flushes the stream.

contd..
5. ws extracts white space characters from input stream. 6. ends - outputs null character. 7. flush flushes the stream. 8. setw(int width) sets the field width. 9. setprecision (int prec) - sets floating point precision. 10. setfill(int base) sets the conversion base 11. setiosflags(long flags) sets the format flag 12. resetiosflag(long flags) resets the format flag.

File Streams
  

Concept of File. File streams Input stream supplies data to the program and output stream receives data from the program. In other words input stream extracts data from the file and supplies it to the program whereas output stream stores data into file supplied by the program.

Hierarchy of File-stream classes


ios

istream

ostream

streambuf

ifstream

fstream

ofstream

contd..


File stream classes


o

filebuf - sets the file buffer to read and write. It contains a constant openprot used in open() of file stream class. It also contains close() as the member. fstreambuf supports operations common to file streams. It serves as base class for te derived classes ifstream, ofstream, and fstream; contains open() and close() as members. ifstream supports input operations. It contains open() with default mode and inherits get(), getline(), read(), seekg(), tellg() functions from istream. ofstream supports output operations. Contains open() with default mode and inherits put(), seekp(), tellp() and write() from ostream. fstream class fstream supports simultaneous input and output operations.

contd..


Opening of Files
o o

Constructor function of the class Member function open() of the class. ios:: in open for reading ios::out open for writing ios::ate pointer at end of file at the time of opening. ios::app all writes occur at eof. ios::trunc truncate the file if exists already. ios::nocreate open fails if file does not exist ios::noreplace open fails if file exists already. ios::binary opens as binary file.

File opening modes


o o o o o o o o

contd..


Closing of Files
o

close()

 

The stream operators >> and << deal with formatted data. Data has to be formatted to produce logical information, as I/O devices communicate with to the computer system using ASCII code.

contd..


C++ I/O system supports four functions for setting a file pointer to any desired position inside file or to get the current file pointer.
Function Member of class Action Performed

seekg seekp tellg() tellp()

ifstream ofstream ifstream ofstream

Moves get file pointer to a specific location Moves put file pointer to a specific location Returns e current position of the get pointer Returns the current position of the put pointer.

contd..


The seek functions set a file pointer to certain offset, relative to the specified origin. The reference point from where the offset is measured is specified as : o ios::beg seek from beginning of the file. o ios::cur seek from the current location. o ios::end seek from end of file.

contd..


ASCII and Binary Files


o

CPU processes the data in binary system. Its hence necessary to convert data while reading /writing. The mode ios::binary.

Persistence Objects o Persistence objects are objects those exist between program executions. o C++ supports persistence objects through concept of file streams.

Exceptions

EXCEPTIONS
 


 

Software Reliability. Software does not degrade physically as a function of time or environmental stress. Changes in computing environment and user requirements need to be accommodated in most applications. Two techniques to build reliable software
Fault avoidance deals with fault prevention by construction. Fault tolerance deals with method of providing services complying with specification inspite of faults having occurred.

C++ exception handling allows to build fault tolerant systems.

  

Fault tolerance begins with error detection. After the error has been detected the next logical step is error recovery. Definition Exception refers to unexpected condition in the program. Exception handling refers to the mechanism through which the error is handled without leading to program fail. Exceptions are of two types synchronous and asynchronous exceptions. Synchronous exceptions they occur during program execution due to some fault in the input-data or technique that is not suitable to handle current class of data. Eg outofrange, overflow, underflow.

contd..

 

 

Asynchronous Exceptions are the ones caused by events or faults unrelated to the program and beyond the control of the program. Eg- hardware malfunctions etc. Exception handling model The exception handling model of C++ uses three blocks or constructs viz.. try, catch and throw. The try block must immediately be followed by catch block. C++ allows exceptions to be of any data type, however it is useful to have them as objects. Exception object carries info from point where exception is thrown to point where it is caught.

contd..

Exception handling model


try block
Perform operation which may throw or invoke exception

throw block
if (failure) throw object;

catch block
Catches all exceptions thrown by try block

try construct defines a boundary within which an exception can occur. catch construct defines the exception handler code. It must immediately follow the try construct. throw construct used to raise an exception when an error is generated in the computation. Sequence whenever an exception is raised the following steps happen.

contd..

1. Program searches for matching handler 2. If a handler is found the program control is transferred to the handler. 3. If no handler is found the program will invoke terminate() function.

C++ makes possible for the user to specify a list of exceptions that a function can throw. Syntax :
Function-Specification throw (type id1, type id2, ..) { // function body raising exceptions if error occurs }

contd..

Catch All Exceptions C++ supports a feature to catch all the exceptions raised in the try-block. The syntax

catch() { // actions for handling an exception }

 

Exceptions in Constructors and Destructors When an exception is thrown, the copy constructor is invoked to initialize a temporary object at throw point. When the program flow is interrupted by an exception, destructors are invoked for all automatic objects which were constructed from entry point of the try block. If the exception is thrown during construction of an object, destructors will be called only for those objects which were fully constructed.

contd..

Handling uncaught Exceptions The uncaught exception handling mechanism relies on two library functions viz.. terminate() the function is invoked when an exception is raised and the handler is not found. Default action for the terminate is to invoke function abort(). unexpected() The unexpected function is called when a function throws an exception not listed in its exception specification.

contd..

Templates

TEMPLATES
 

Templates provide for re-usability and elimination of redundant programming; Templates support generic programming developing reusable software components supporting different data types in a single framework. Generic data types They are the arguments of the template type. C++ offers templates in two forms function templates and class templates

Function Templates
 

Function templates provide a mechanism for creating a single function possessing the capability of several functions; Function templates make possible to have one source declaration that can produce multiple functions differing only in their data types. Gen format :
template <class T1, class T2, > returntype function-name (Arguments of type T1, T2,..) { //local variables of type T1, T2; // local variables operating on T1, T2 ; // other variables }

In Function templates  The syntax remains same to normal functions except that the data types of variables are not known until they are invoked.  The unknown data types are resolved and expanded to respective data types at compile time.  Function call of template function is similar to that of normal function. It can be called with arguments of any data type.  The compiler internally creates functions depending on the data types of the input parameters.

contd..

Template Function Overloading A template function can be overloaded in two ways.


o o

contd..

By other functions of its name; (non-template function) By other template functions of the same name.

The overloaded functions must differ either in terms of number of parameters or their types. There are two ways of resolving the overloading issues
o o

If an exact match is found, call it If a function can be generated from a function template, call the generated function

Function templates support nesting of function calls, the concept used in implementing recursion.

Multiple generic Function Templates F.T.s support declaration of multiple parameters; in such a case they require multiple generic arguments. User Defined Template Arguments It is possible to pass user defined types to function templates.

contd..

Class Templates
can be declared to operate on different data types, such classes are called as class templates.  Class template specifies how individual classes can be constructed similar to normal class specification.  Class template model a generic class which support similar operations for different data types. Eg. Generic stack.
 Classes

Class template declaration template <class T1, class T2, ..> class class-name { T1 data1; T2 data2; .. void func1( T1 a, T2 &b); .. T func2(T2 *x, T2 *y); };

contd..

 

Member function Templates A member function of a template class is implicitly treated as a template function and it can have template arguments which are same as its class template arguments. Inheritance of class template A combination of templates and inheritance can be used in developing hierarchical data structures; The base class in the hierarchy represent a commonality of methods and properties.

contd..

 

Use of templates with inheritance involves following issues Derive a class template from base class, which is template class Derive a class from base class which is a template class and add more template members in the derived class. Derive a class from the non-template base class and add template members to it. Derive a class from a base class which is base class and restrict the template feature.

contd..

Template class inheritance : template <class T1, .> class BaseClass { // template type data and functions }; template <class T2,..> class DerivedClass : public BaseClass <T1, .> { // template type data and functions };  The class template can also be declared for a class having operator overloaded member functions. The syntax for declaring operator function is same as that of normal class.


contd..

Iterator
 

In C++, an iterator is an object which points to some element in a range of elements e.g. an array, a container, etc. Iterator iterates through the elements of that range using a set of operators viz.. ++, *. Categories of Iterator


Pointer A pointer can point to elements in an array, and can iterate through them using the increment operator (++). Each container type has a specific iterator type designed to iterate through its elements in an efficient way.

C++ provides for 5 different types of iterators depending on the functionality they implement.


Forward ; Bidirectional ; Random Access ; Input; Output.

Forward iterators have all the functionality of input and output iterators; they are limited to one direction in which to iterate through a range.  Bidirectional iterators can be iterated through in both directions. All standard containers support bidirectional iterators types.  Random access iterators implement access ranges nonsequentially; offsets can be directly applied to these iterators without iterating through all the elements in between. Also Random access iterators have all the functionalities of bidirectional iterators.  Input and output iterators perform only sequential input or output operations.

contd..

 

Iterator base class This is a base class template that can be used to derive iterator classes from it. This base class only provides some member types, which in fact are not required to be present in any iterator type Iterator types define the members needed for the default iterator_traits class template to generate the appropriate iterator_traits class automatically. Definition template < class Category, class T, class Distance = ptrdiff_t, class Pointer = T*, class Reference = T& > struct iterator { typedef T value_type; typedef Distance difference_type; typedef Pointer pointer; typedef Reference reference; typedef Category iterator_category; };

contd..

iterator_traits  Used in standard algorithms, to determine the characteristics of the iterators passed to them.  For every iterator type, a corresponding specialization of iterator_traits class template exists.  Definition
template <class Iterator> struct iterator_traits { typedef typename Iterator::difference_type difference_type; typedef typename Iterator::value_type value_type; typedef typename Iterator::pointer pointer; typedef typename Iterator::reference reference; typedef typename Iterator::iterator_category iterator_category; }

contd..

String objects are a special type of container, specifically designed to operate with sequences of characters. C++ string objects belong to a class with many built-in features to operate with strings The class also provides for additional useful features common to C++ containers. String class is an instantiation of the basic_string class template, defined in <string> as: typedef basic_string<char> string;

String class

contd..
       

String class members the member functions of the String class can be categorized into : Constructor Operator Iterators Capacity Element access Modifiers String operations

Constructor functions
     

contd..

string ( ); string ( const string& str ); string ( const string& str, size_t pos, size_t n = npos ); string ( const char * s, size_t n ); string ( const char * s ); string ( size_t n, char c ); template<class InputIterator> string (InputIterator begin, InputIterator end); string& operator= ( const string& str ); string& operator= ( const char* s ); stringmoperator= ( char c );

Operator functions
  

 

Iterators: begin returns iterator to first character in the string.


o o

contd..

iterator begin() const_iterator begin() const; iterator end(); const_iterator end() const;

end returns iterator to the end.


o o

rbegin - returns a reverse iterator referring to the last character in the string, which is considered the reverse beginning.
o o

reverse_iterator rbegin(); const_reverse_iterator rbegin() const;

rend rend refers to the character right before the one that would be referred to by member begin.
 o

reverse_iterator rend(); const_reverse_iterator rend() const;




Capacity
size
size size_t size()

contd..

Returns a count of the number of characters in the string.




length
size_t length() Returns a count of the number of characters in the string.

capacity
size_t capacity() Returns the size of the allocated storage space in the string object.

clear
void clear() The string content is set to an empty string erasing previous content and setting the size to zero characters.

empty
bool empty() ; Checks whether the string is empty or not.


o

Element Access

contd..

operator [] char& operator[] (size_t pos) returns a reference at position pos in the string. at char& at(size_t pos) returns the character at position pos in the string.


o

Modifiers

operator +=  string& operator += (const string& str)  string& operator += (const char* s)  string& operator += (char c) Appends a copy of the argument to the string. The new string is the content existing in the string object before the call followed by content of the argument.

append() appends the string at given position


    

contd..

string& string& string& string& string&

append ( const string& str ); append ( const string& str, size_t pos, size_t n ); append ( const char* s, size_t n ); append ( const char* s ); append ( size_t n, char c );

String operations
o


copy() appends the string at given position


size_t copy ( char* s, size_t n, size_t pos = 0)

Copies a sequence of characters from the string content to the array pointed by s. The sequence of characters is made of the characters in the string that start at character position pos and span n characters from there.

A container is a holder object that stores a collection other objects. They are implemented as class templates. The container manages the storage space for its elements and provides member functions to access them, either directly or through iterators. Containers replicate structures very commonly used in programming:
      

STL Containers

dynamic arrays (vector), queues (queue), stacks (stack), heaps (priority_queue), linked lists (list), trees (set), associative arrays (map)...

  o o o

Container class templates Sequence containers: vector Vector (class template ) deque Double ended queue (class template ) list List (class template ) Container adaptors stack LIFO stack (class template ) queue FIFO queue (class template ) priority_queue Priority queue (class template)

contd..

 o o o

Associative containers : o set Set (class template ) o multiset Multiple-key set (class template) o map Map (class template ) o multimap Multiple-key map (class template ) o bitset Bitset (class template)

contd..

Many containers have several member functions in common, and share functionalities. The decision of which type of container to use for a specific generally depends on the functionality offered by the container and on the efficiency of some of its members (complexity). Container adaptors are classes that provide a specific interface relying on an object of one of the container classes (such as deque or list) to handle the elements. The underlying container is encapsulated in such a way that its elements are accessed by the members of the container class independently of the underlying container class used. stack, queue and priority_queue are implemented as container adaptors.

contd..

 

STL Algorithms The header <algorithm> defines a collection of functions especially designed to be used on ranges of elements. A range is any sequence of objects that can be accessed through iterators or pointers, such as an array or an instance of some of the STL containers. Algorithms operate through iterators directly on the values, not affecting in any way the structure of any possible container

contd..

 
     

Functions in <algorithm> Non-modifying sequence operations:

contd..

 

for_each Apply function to range (template function) find Find value in range (function template) find_if Find element in range (function template) find_end Find last subsequence in range (function template) find_first_of Find element from set in range (function template) adjacent_find- Find equal adjacent elements in range (function template) Count Count appearances of value in range (function template) count_if Return number of elements in range satisfying condition (function template) mismatch Return first position where two ranges differ (function template)

contd..
  

     

equal Test whether the elements in two ranges are equal (function template) search- Find subsequence in range (function template) search_n - Find succession of equal values in range (function template) Modifying sequence operations: copy Copy range of elements (function template ) swap Exchange values of two objects (function template) replace Replace value in range (function template) remove Remove value from range (function template ) reverse Reverse range (function template)

contd..
    

Sorting: sort Sort elements in range (function template) partial_sort Partially Sort elements in range (function template) Binary search (operating on sorted ranges): lower_bound Return iterator to lower bound (function template) upper_bound Return iterator to upper bound (function template) equal_range Get subrange of equal elements (function template) binary_search Test if value exists in sorted array (function template)

NameSpaces

Modular structure of programming, imposes conditions to minimize dependencies between modules.


Eg.. Error/Exceptions in one module should not affect the related modules.

Name Spaces

Naming of variables, constants and other user defined entities is also an issue, in large programs. Each module in the memory is allocated its own address space. Modularity demands safe, convenient and efficient communication across module boundaries. Modular programs may not always be sequential, but also concurrent;

Namespaces contain classes, objects, functions and data logically combined into a single unit. Namespace basically provides a scope. Exclusively used in large programs to group it into logically linked units. General Syntax namespace variable { class classname { }; return type function { .} } Eg : namespace samp { class example { } ; void f1(); }

contd..

  

Accessibility The members of the namespace can be accessed by the keyword using or ::  samp::example ob1, ob2; or  using namespace samp;  example ob1, ob2; Also the members can be declared inside and defined outside. In such case the namespace definition is in one address space and function definition is in other address space. Namespace is a mechanism which aids in developing efficient modular programming.

contd..

 

Two classes having same names can be put under different namespaces. Namespaces can be nested. All the files in the standard C++ library declare all of its entities within the std namespace. Namespace alias : Alternate namespace name for the existing namespace.  namespace new_name = existing_name;

contd..

Namespace supports overloading. Overloading is used to migrate existing name spaces with minimal changes.

Unnamed namespaces A name space can be unnamed. In such a case, the compiler generates a unique name to it.used to protect namespace from outside access. Unnamed namespaces have implied using directive. (Concept similar to unnamed variables accepting return values). Name space aliases : namespace Chennai_Bangalore_Express { .. .. } Namespace CBE = Chennai_Bangalore_Express ;

contd..

Run Time Type Identification

Run Time Type Identification


 

RTTI is used to navigate the class hierarchy. In inheritances other than single there are more than one base classes. Also if the said base class appears more once in the hierarchy, caution needs to be exercised when the base class object is referred. There are two situations when a base class object needs to be referred  When explicit naming of base class object happens;  When a pointer to the object representing base class needs to be declared. Navigation of class hierarchies involves using type conversions to gain a pointer of the desired type.

Casting  Static cast happens at compile time.  Dynamic cast casts from polymorphic virtual base class to a derived class. The operation requires a polymorphic operand, used to find objects for which it represents a base.  Both the type of casts obey the rules of const and access controls. Its not possible to cast to a private base class.  Dynamic cast provides information about the type of an object at runtime. Ensures that code written using it works correctly with classes derived from those explicitly mentioned by the programmer.

contd..

 

dynamic_cast operator performs the type conversion operation and returns a valid pointer if the object is of expected type and null pointer if it isnt. The dynamic_cast operator takes two operands a type bracketed by < and >, and a pointer or reference bracketed by ( and ). Syntax : dynamic_cast <D*> (p) Note: If p is of type D*, or an accessible base class of D, the result is of assignment operation p to D*.

contd..

contd..
  

It is needed to know the exact type of the object, or layout, or name of its class. The typeid operator is used for this purpose. typeid is exclusively used to find the type of an object referred to by a reference or a pointer. RTTI offers to user the information about pointers and references which is similar to type information a compiler maintains while compiling a C++ program. RTTI works in two ways  Getting type information from run-time elements like pointers and references  Getting type information from static elements like classes.

contd..
 

The typeid() returns a reference to a standard library type_info that represents the type-name. The above information is passed on to the user in the form of a runtime object. Such an object is type-id and keeps all information which characterizes a C++ type. type-id: The typeid for a pointer or reference will represent the type of the actual object pointed by that pointer or referred to by that reference. The typeids can be retrieved from existing C++ classes or pointers to objects of these classes. The typeids can also be created at runtime and treated as compiletime type.

Multi Threading

Introduction
 

Processes A process can be considered to be a container of threads within a protected addressspace. o Parts of the address space may be shareable o One or more threads execute through this space A process represents a protected region of address space, a fully encapsulated unit and shares its data by some interprocess communication (IPC) mechanism; e.g..via named pipes or shared memory. Multiple processes execute concurrently o Multiple processors, pre-emptive multitasking or, in the worst case, co-operative multitasking

contd..


A process consists of a program


 

statements are performed in an independent memory area; a program counter that remembers which statement should be executed next; a stack which holds the arguments passed to functions as well as the variables local to functions; there is a heap which holds the remaining memory requirements of the program.

It is productive to arrange for two or more processes to work together to accomplish one goal. Two approaches :
 

design the program to use multiple processes or design the program to use multiple threads.

Threading is a mechanism for splitting the workload into separate execution streams. A thread is lighter weight than a process.  thread offers less flexibility than a full blown process,  can be initiated faster because there is less for the Operating System to set up.  threads have no separate address space; all the threads share a single memory space and also share a single heap.  each thread is given its own stack. POSIX a standard for the threads. The POSIX 1003.1

contd..

standard based on UNIX is an ISO standard that specifies operating system functionality in a C language interface.


The threading model used is the POSIX threading interface, often called pthreads.

 

Types o Single process single threaded o Single process multi threaded Threads Execution is subject to priorities and policies.
o

contd..

o o

A thread is an identifiable flow of control within a process, with its own stack A sequential process without interrupts has a single thread A sequential process with interrupts has a single main thread and other notional short-lived threads

 

Other types of process considered multithreaded Thread execution is also dependent on platform and program priorities and policies

contd..
 

 

Synchronization between threads In threading, the multiple threads if don't interact with one another, do not corrupt each other's data. If there is interaction, then, the corruption is very difficult to debug, and makes multi-threaded programs very time consuming The solution is to synchronize whenever shared data is accessed (either written or read). Semaphores A semaphore is a synchronization object. A thread must, in general, synchronize itself with other threads to properly execute a multithreaded program.

 

Mutex Mutex meaning mutual exclusion is to ensure only one thread is accessing a particular section of the code. o When one thread locks the mutex, it has exclusive access to that section of code until it unlocks the mutex. o If a second thread tries to lock the mutex while another thread has it locked, the second thread will be block until the mutex is unlocked and is once more available.

contd..

 

Zombie Process and Orphan Process A zombie process or defunct process is a process that has completed execution but still has an entry in the process table. This entry is still needed to allow the process that started the (now zombie) process to read its exit status An orphan process is a computer process whose parent process has finished or terminated, though itself remains running. An orphaned process will be immediately adopted by the special init system process. This operation is called re-parenting and occurs automatically. Even though technically the process has the "init" process as its parent, it is still called an orphan process since the process that originally created it no longer exists. Both are commonly seen in UNIX.

contd..

 

A daemon is a computer program that runs in the background, rather than under the direct control of a user; they are usually initiated as background processes. Systems often start (or "launch") daemons at boot time; they often serve the function of responding to network requests, hardware activity, or other programs by performing some task. Daemons can also configure hardware, run scheduled tasks, and perform a variety of other tasks. In a Unix environment, the parent process of a daemon is often (but not always) the init process (PID=1). Processes usually become daemons by forking a child process and then having their parent process immediately exit, thus causing init to adopt the child process.

contd..

Socket Programming

Vous aimerez peut-être aussi