Table of contents
- Differences in C and C++
- Basic features of an OOP
- Basic Components of a C++ programming languages
- Structure of C++ Program
- Stages in executing a C++ Program
- Control Statement
- Arrays
- Function
- Storage classes
- Classes
- Objects
- Access specifiers
- Constructors
- Types of Constructor in C++
- Operator overloading
- Operators that cannot be overloaded
- Inheritance
- Types of Inheritance
- Polymorphism
- Types of Polymorphism -
- Command Line Arguments
- Preprocessor Directives
- Basic Class Template
- Element of the iostream library classes
- Basic Stream Concepts
- Flags & the bit fields for self() function
- Two ways to open a file
- For reading & writing the data
- File Mode Parameters
- Some Useful Functions :
- Function Templates
- Template Instantiation
- Three major Components in STL mainly
- The 3 types of sequence containers in the STL :
- Exception Handling
- Exception Handling Mechanism
- Standard exception
- Conclusion
C++ is OOP as well as a conventional procedural programming language.
OOP enables one to put (data) & (function) in one container (object).
1st version of a programming language is a machine-level language(1940s) in binary code as a low-level language.
High-level programming was introduced in the year 1970.
Languages | Developer | Year of introduced |
FORTRAN | John Backus | 1957 |
PASCAL | Niklaus Wirth | 1970 |
C | Dennis Ritchie | 1973 |
C++ | Bjorn Stroutrup | 1980 |
Differences in C and C++
Parameter | C | C++ |
Programming Paradigm | Procedural programming lang | Object-oriented programming lang |
History | 1972 by Dennis Ritchie | 1979 by Bjorn Stroutrup |
Approach | top-down approach | Bottom-up approach |
Keywords | 32 | 63 |
Data Types | built-in | built-in & user-defined |
File Extension | .c | .cpp |
Header File | <studio.h> | <iostream> |
Allocation & Deallocation of memory | calloc() ,malloc() & free() | new operator - delete operator |
Access Modifier | Does not support | support |
Security | No | Yes |
Functions in the object are known as member functions(Methods).
Basic features of an OOP
Objects - real-world entities, data, functions, methods
Classes - group of object(same property & common)
Inheritance - the process of deriving the properties to another
Polymorphism - the ability to present the same interface in different forms, many forms of a single object
Encapsulation - used to bind code & data together combining data & function in one unit.
C++ is a superset of C.
C++ ends with a (;)
Reverse words are written in small cases.
Basic Components of a C++ programming languages
- Data Types - int, char, float, double
Modifiers - Signed, unsigned, long, short
- Variables - container of data, they are names used to refer to memory location
Note - Declare variable before being used
- Token in C++ :-
i) Identifier - Use to define a name, mostly used to name variables(array, structure, functions, classes)
ii) Keywords - they are reserved words
Ex - auto, break, catch, class, delete, do, for, new, int, long, mutual, public, protected, return, size of, signed, void, while
iii) Constants - It can be numeric, character or string value of a constant does not change
iv) Operators - Rich set of operators
Arithmetic Operators(+,-,*,/,%,++ ,--)
Relational Operators(<,>,>=,<=,== ,!=)
Logical Operators(&& , || , !)
Bitwise Operators(& , | , ^ , ~)
C++ I/O methods - cin,court
Include header file iostream.h defines cin & cout
cout(<<) - insertion operator
cin(>>) - extraction operator
Structure of C++ Program
Documentation Section
Header file Section
Class Declaration or Definition Section
Class Function Definition Section
Main() function Section
Stages in executing a C++ Program
Compiling - the process of converting source code to machine code
Linking - the process of combining the compiled code with libraries and other object files to create an executable program.
Running - the process of executing the compiled and linked executable file on the computer, performing the program's intended operations.
Control Statement
It executes program statements sequentially based on the condition
Types of Control Statements in C++ :
Conditional Statement -
i) if
if(expression or condition)
{
statement 1;
statement 2;
}
ii) if-else
if(expression or condition)
{
statements ;
}
else
{
statements ;
}
iii) Nested
if(condition 1)
{
if(condition 2){
statement 1;
statement 2;
}
else if(condition 3)
{
statement 3;
}
else
{
statement 4;
}
// multiple conditions can be check using logical and & or operator
if((condition 1) && (condition 2))
statement 1;
else
statement 2;
iv) switch
switch (varible name)
{
case constant 1:
statement 1;
break;
case constant 2:
statement 2;
break;
case constant 3:
statement 3;
break;
default :
default statement;
}
- Conditional Operator(?)
(condition) ? True statement : False statement ;
- Unconditional Statement -
i) break
ii) continue
iii) exit
- Iteration Statements - loop causes a block of statements to execute repeatedly
- for loop
for(initialization ; condition ; increment/decrement)
{
//body of for loop;
statement 1;
statement 2;
}
- while loop
while(condition)
{
//body of the while loop
statement 1;
statement 2;
}
- do while loop
do
{
statement 1;
statement 2;
}
while(condition statement);
{
statements;
}
Arrays
- It is a collection of elements of the same data type, array values known as array elements
Declaration & Definition of arrays
Ex-
int x[10] , x[0] , x[1] to till x[9]
Initialization of array
Ex -
int a[5] = {3,6,9,12,15} or a[] = {3,6,9,12,15}
- Pointers - they are variables that store address values of other variables, defined by “*” prefixing to a variable name, the datatype of the pointer variable can be a user-defined data type or even void
Function
a group of statement that performs a task together
Types of Functions:-
Predefined Functions - standard library functions (strcpy , strlen)
User-defined Functions - defined by the user (should be declared before used)
- Declaration of Functions -
function_name
return_type
set of parameters (parameter list)
syntax -
return_type function_name (parameter list)
Input to functions can be passed through parameters
During the declaration of the function along with the parameter name, the data type of parameters, more parameters should be separated with a comma(,)
Definition of a function - it provides the actual body of the function
Function syntax -
return-type function_name (parameter list) // function header { statements; // function body }
Passing Data to functions
Pass by value
Pass by reference
- Function default arguments -
Values need not be explicitly passed during function call & should be specified at the end of the argument list to avoid function overloading.
Case 1 : No argument is passed
void temp(int = 10 , float = 8.8);
int main(){
........
temp();
........
}
void temp(int i , float f){
// code
}
Case 2 : first argument is passed
void temp(int = 10 , float = 8.8);
int main(){
........
temp(6);
........
}
void temp(int i , float f){
// code
}
Case 3 : all argument are passed
void temp(int = 10 , float = 8.8);
int main(){
........
temp(6,-2.3);
........
}
void temp(int i , float f){
// code
}
The array can be used as arguments to functions
Scope & Visibility of variables in function
Functions help to save memory as all the calls to the function use the same code for execution
- Incline Functions - It is used to reduce the size of the code & improve the speed of program execution, it should be defined before the main() function declaration begins with the keyword “inline”.
syntax -
inline return-type name_of_function(arguments)
{
statements of function; // functions body
}
Storage classes
It defines the scope & lifetime of variables or functions to determine when a variable is allocated, how long it lives, how long it is accessed, and where it is stored.
Types of storage classes -
Automatic*-* It is also called local variables, the keyword “auto” is used to declare automatic variables, scope is within the function block, and lifetime is limited & hence it saves memory.
External - variable defined outside/external to any functions. reorganized globally, it can used by multiple functions & is automatically initialized to zero.
Static - the scope of static variables is within the function also like automatic variables & these are initialized & storage space is allocated only once at the beginning.
- String - used to declare & initialise string value easily can store character names like name, address, and password. are similar to arrays, also defined during the declaration statement. they are terminated by a null character (’/o’) to mark the end of the string
String library Function | Meaning | Syntax |
strlen() | used to find the length of the string | strlen(string variable) |
strrev() | used to arrange the characters in reserve order except the null character | strcpy(destination string, source string) |
strcpy() | used to copy the contents of one string to another | |
strcmp() | used to compare two strings |
- Structures - grouping elements with dissimilar types can also copied & assigned to another structure variable.
syntax -
Struct name
{
datatype member1;
datatype member2;
....
....
};
Enumerated datatype - enables the user to create their datatype defines using keyword enum.
Unions - It can hold only one of its non-static data members at a time.
Classes
It Provides users a way to create user-defined data types, it binds data & functions objects in an instance of a class
Objects have a similar relationship with classes as variables have with data type.
Characteristics of Class:-
Class is a template that units data and operations
It is an abstraction of real-world entities
The class identifies a set of similar objects.
syntax of class -
Class classname
{
variable declaration;
function declaration;
}
Objects
It can hold a similar relationship with classes as a variable holds with a datatype. an instance of a class is known as an object of the class & is used in the program to store data & declare in the program like a variable declaration.
Objects are created by using the class name followed by the object name.
Creation of objects -
1) Product p1 ; // declare p1 object of the type product
Product p2 ; // declare p2 object of the type product
//here p1 & p2 have own copy of data members
2) Product p = Product(); // value initialization
// parenthesis can supply constructor arguments
Access specifiers
Access modifiers are used to implement an important aspect of OOP use for data handling.
Types of access specifiers -
Private -
Public -
Protected -
syntax of declaring access specifiers in C++ -
className
{
private : // declare private members/ methods here
public : // declare public members/ methods here
protected : // declare public members/ methods here
Access Specifier | Same class | outside class | derived class |
Public | Yes | Yes | Yes |
Private | Yes | No | No |
Protected | Yes | No | Yes |
Arrays in Objects - The array data can be of any type including struct, so arrays of variables of type class & those variables are called arrays of objects.
Functions in Objects -
syntax -
void (distance , distance);
or
distance add(distance);
- Pointers in Objects - They can point to simple data types, arrays and objects as well
Class Objects
| |
item A;
item *iptr;
- Abstract class - It acts like a base class that can be inherited by other classes. It is not used to create objects. specify it with a pure by placing “=0” in its declaration.
syntax -
Class container
{
public :
virtual double getvolume() = 0; // pure virtual functions
private :
double length; // length of a box
double breadth; //breadth of a box
double height; // height of a box
};
this Pointer - Whenever the program creates a class instance, a special pointer is developed in C++ called this & it contains the address of the current object instance.
Features of this Pointer -
Stores the address of the class instance, to enable Pointer access of the members to the member functions of the class.
It is not counted for calculating the size of the object.
Not accessible for static member functions
Can’t be modified
friend functions- It allows us to access some non-member functions & private as well as protected class members can be accessed by friend classes, we can declare a friend function anywhere in the class declaration
If you want to declare an external function as a friend of a class thus allowing this function to have access to the private & protected members of this class
friend class - used when two classes are strongly coupled
friend Scope - scope of a friend class name is the first non-class enclosing scope. that is use the scope resolution operator (::) if the friend function is a member of another class.
A static data member of the class is one data member that is common for all the objects of the class and is accessible to the class. can store some common data about the class like the count of the number of objects created for a class. use prefix static to declare static data members & static functions.
Constructors
It is a special member function of a class whose task is to initialize the object of the class and it has the same name as that of the class.
It is called a constructor because it constructs the value of data members at the time of object initialization
Complier invokes a constructor whenever an object is created & it defines value to a data member, so it has no return type.
syntax -
class classname
{
public :
classname(); // constructor
classname(argument list); // another constructor
....
};
- Characteristics of a constructor -
Having the same name as its class, initialize class members when the object of the class is created.
Should be declared in the public section of class for availability to other functions
No return type, not even void.
Cannot be inherited, but the derived class can call the constructor of its baser class.
They call member functions of their class & cannot be virtual
Have default values & can be overloaded.
Can create multiple constructors of the same class but with different parameters
Types of Constructor in C++
- Default Constructor - It does not take any argument, it has no parameter & it is important for the initialization of object members, that even if it does not define a constructor explicitly, the compiler provides a default constructor implicitly.
syntax -
Class class_name
{
Private :
....
....
Public :
class_name()
{
....
}
}
- Parameterized Constructor - It is a class that can take parameters & used to initialize objects with a different set of values.
syntax -
class classname
{
.....;
.....;
public:
classname (parameter list)
{
.....;
}
};
- Copy Constructor - A special type of constructor that takes an object as argument, and is used to copy values of data members of one object into another object. It is used for the creation of an existing object & used to initialise the thing from another of the same type.
syntax -
classname (const classname ,&object)
{
.......;
.......;
}
- Dynamic Constructor - Used to allocate the memory while creating the objects, the data members of an object after creation can be initialized.
- Destructor - It is a special class function that destroys the object as soon as the scope of the object ends. It is automatically called a destructor by the compiler when the object goes out of scope.
syntax -
class classname
{
public :
~classname() // defining destructor for class
{
// statement
}
};
- Namespace - It is a certain scope for identifiers, there are always chances of name class if we use different modules or libraries; the reason is that these modules or libraries use the same identifier for many things & issue is resolved by using namespace in C++
syntax -
namespace namespace_name
{
//code declarations
}
Operator overloading
we can specify the way the different arithmetic, relational & other operators work with user-defined data types or classes.
Operator overloading modifies the functionality of the existing operators. so that they can be used with user-defined data types such as classes, But it is not possible in C++ to add the two objects of the class with the same ‘+’ operator, so we use operator overloading
In C++, unary, binary & special operators can be overloaded.
List of functions that can be overloaded
+ | - | * | / | % | ^ | & | ~ | |||
! | \= | < | \> | += | -= | *= | /= | %= | ||
^= | &= | = | << | \>> | << = | \>> = | \== | ! = | ||
< = | \> = | && | ++ | - - | , | -> * | -> | |||
() | [ ] | new | new[] | delete | delete[] |
Operators that cannot be overloaded
dot operator(.)
The reference pointer to class member ()*
scope resolution operator (::)
size of operator
preprocessor symbol (#)
- Operator Functions - Used to overload an operator. defines the operations that the overloaded operators will perform on the objects of the class for which it is redefined.
The operator function is defined either as a public function or as a friend function
- Steps to overload an operator
Create the class for which an operator is to be overloaded.
Declare the functions either as a public or a friend function.
Define the operator either inside the class definition (member function) or outside the class (friend function).
syntax to define the member operator function inside the class:-
return_type operator op(paramter_list)
{
// function body
}
Ex -
int operator + (int a , int b)
we also define member function outside the class you have to declare it first inside the class
syntax to define the member operator function inside the class:-
return_type class_name :: operator op(paramter_list)
{
// function body
}
Ex -
int test :: operator + (int a , int b)
/* 1) here return_type (int) = data type of the value returned by the function operator is C++ keyword
2) op(+) is the name of the operator to be overloaded , as well the name of the operator overloaded function
3) parameter_list(int a, int b) is the list of arguments passes to the operator function
4) class_name is the name of class to which the object belong */
- Rules while overloading operators -
overloading function can be either a nonstatic or non-member function with at least one parameter that has a class.
precedence & associativity of the operator cannot be changed.
(Unary, binary, or ternary) is an operator that cannot be changed
Operator - = , [],() & - > can be overloaded only as member functions & not as friend function
Except for assignment operator ‘=’ all the overloaded operators can be inherited by a derived class
- The benefits of operator overloading are -
Make the program easier to read
Provide the operator with a special meaning for a datatype.
- Drawbacks of Operator Overloading -
- In extreme cases, the + operator is redefined to mean minus & the _ operator is redefined to mean plus, this probably will not occur very often, but more subtle cases are conceivable.
- Overloading Unary operator -
Operators are the ones that operate a single operator. some of the unary operators are (++) & (--) & (-) & (!) and the calling operand can be used on either the left & right side of the operator in increase and decrease operator, also for class keyword operator is used.
- Overloading Binary Operator -
Operators that require 2 operands for operation such as arithmetic operator (+, *, / ,etc.), relational operator (<, >)
Here one operand is an object of the class invoking the function and is passed implicitly to the member operator function while the other operand is passed as an argument, which can be passed either by value or by reference
Type Conversions - It is defined as the process of converting one predefined data type to another
An assignment operator performs the automatic type conversion
Situations may arise in data conversion between incompatible types.
Conversion from basic to class type
Conversion from class type to basic type
Conversion from one class type to another class type
- Conversion between objects of different classes can be done through either a conversion function or by a constructor.
Inheritance
It is the process of creating new classes known as derived classes from the existing or base class. It's a mechanism of reusing & extending classes without modifying them, thus producing hierarchical relationships between them. It is almost like embracing an object into a class.
Advantages of inheritance in OOPs -
Reusability of the code
Time & Efforts are being saved
Improve program structure which can be readable
Easy to Debug
- Disadvantages of Inheritance in OOPs -
Classes are dependent on each other. i.e. base & superclasses are tightly coupled
The functionality of the base class is changed changed then the changes have to be done on the child classes also.
Methods in the superclass are deleted then it is very difficult to maintain the functionality of the child class.
syntax -
class subclassname : access specifier superclassname
{
// class specific code;
};
class child_class : access specifier parent_class
{
// class specific code; // |class A| parent/super/base class
}; // |class B| shild/sub/derived class
- Public, Private and Protected Inheritance
A derived class can be defined as:
syntax -
class derived_classname : access specifier baseclass name
{
member of derived class
};
- Access Specifier Public -
Base Class | Derived Class | |
inherited Public Member | → | public member |
inherited Protected member | → | protected member |
inherited Private number | → | private to base(cannot be accessed) |
- Access Specifier Private -
Base Class | Derived Class | |
inherited Public Member | → | private member |
inherited Protected member | → | private member |
inherited Private number | → | (cannot be accessed) |
- Access Specifier Protected -
Base Class | Derived Class | |
inherited Public Member | → | protected member |
inherited Protected member | → | protected member |
inherited Private number | → | (cannot be accessed) |
Types of Inheritance
- Single inheritance - A class drives from one base class only, which means that there is only one subclass that is derived from one superclass
syntax -
class subclassname : access Specifier superclassname
{
// class specific code;
}
- Multiple Inheritance - A class drives from more than one classes
syntax -
class subclassname : access Specifier superlcassname1, superclassname2
{
// class specific code;
}
Hierarchical Inheritance - Here more than one class inherits from a single base class
Hybrid Inheritance - A combination of more than one type of inheritance & a new class can be created from multiple & multi-level classes.
- Function Overriding - If a class is inherited in the derived class, and if one of the functions of the base class is again defined in the derived class, then that function is said to be overridden & this procedure is known as function overriding.
To access the base class, use the base class name and then the scope resolution operator(:)
- Ambiguity in multiple inheritance - It can be resolved by prefixing the parent class name followed by the scope resolution operator before the function name.
syntax - Obj.P :: function1()
- Constructor in Derived classes -
Create objects using the derived class, then it makes sense for the derived class to pass arguments to the base class constructor.
- Points to Remember -
Orders of constructor calling:- child → Parent
Orders of constructor execution:- Parent → child
Orders of destructor calling:- child → Parent
Orders of destructor execution:- child → Parent
Polymorphism
It means the same content but different forms, Poly(many) & morphos(form), here the same program code can call different functions of different classes
The advantages of Polymorphism are -
Helps in the reusability of code
Provides easier maintenance of applications
Helps in achieving robustness in applications
Types of Polymorphism -
- Compile time polymorphism - It is referred to as static binding or early binding & it takes place during compilation. i.e. an object is bound to its function call at compile time
i) Function Overloading - In C++ two or more functions can have the same name if the number and /or type of parameters are different.
They are based on the no. & type of parameters passed
ii) Operator Overloading - It is function overloading, where different operator functions have the same symbol but different operands
It is used to overload or redefine most of the operations like + - * /=, = etc.
syntax -
class class_name
{
...
...
public:
return_type operator symbol(argument())
{
...
...
}
....
};
- Run time polymorphism - Here binding or liking of a function definition to a specific function call is done during run-time.
i)Function Overriding - It can have the same function in the base class as well as its derived classes.
when we call the function using an object of the derived class the function of the derived class is executed instead of the one in the base class. so, different functions are executed depending on the object calling the functions
ii)Virtual Function - Using this in the base class ensures that the function can be overridden in these cases. it is a member function that we expect to be redefined in the derived classes.
A virtual function is a function that is overridden which means it is declared in the base class using a virtual keyword & its functionality is redefined by its derived classes.
iii) Pure Virtual Function - a pure virtual function is a virtual function with the definition, most of the time the idea behind declaring a function virtual is to stop its execution.
File input & output is completely handled by predefined file & stream & stream-related classes
cin & cout Statements - Its predefined objects of these predefined stream
cin : Transfer input from keyboard
cout : Transfer output to display screen are also classes
above declarations of the stream classes are contained header file ’iostream.h’
A stream is a flow of characters flow of characters flow is into the program is call ’input stream’. flow is out of the program then it is called the output stream’
All stream classes are inherited from the ios class & it provides support for formatted/Unformatted I/O operations
It contains many constraints & member functions that can be used by all other input & output classes & are present in the ios class
istream(input stream) class is derived from ios class.
some functions that are defined in this class are get() , getline(), read() & overloaded extraction operations(>>)
ostream (output stream) class is derived from ios class & performs all types of output-related functions like put() write()
Overload insertion operator(<<) is defined in this class
Stream buf class provides the interface to physical devices through buffers
3 classes → istream_with assign,
ostream_withassign, iostream
Files used for both input-output operations are inherited from the class - fstream & fstream class is inherited from both iostream & fstream base
Classes fstream , ifstream & ofstream are declared in the fstream.h header file.
the file fstream.h also includes iostream.h , so the programs using fstream.h need not explicitly include iostream.h
Character and string input & output to files
It represents the ways to read characters & strings from the text file and to write it to the text file
To write a character to a file, we need to create an object of ofstream class & here put() function is used with the objects & it writes one character at a time.
syntax -
objectname.put(character variable)
Insertion operator (<<) → It is overloaded in the ostream class (ofstream is derived from ostream) & use along with the ofstream object to write text directly to the file.
ifstream class → These objects are used to read data from the file with get() or getline() function here, get() reads one character at a time
object name is an object of ifstream class & character to be read from the file is stored in a variable
syntax -
objectname.get(character variable)
Note - use eof() function & return non -zero value when an end of file is encountered & returns zero when reading the file.
getline() function is also use to read contents from a file & this function reads the contents line by line
The Extraction operator(>>) → It can be used with an ifstream object to read the text as this operator is overloaded in the istream class.
ifstream is derived from istream, it reads one word at a time.
Command Line Arguments
- the optional string arguments that are given by the user to a program during execution are known as ‘command line arguments’.
To pass two arguments in the main function i.e. argc & argv
Ex- int main(int argc , char* argv[])
Here argc is an argument containing the no. of arguments passed to the program
the 1st parameter, argc(argument count) is an integer that indicates how many arguments were entered on the command line when the program was started.
2nd parameter, argv (argument vector), is an array of pointers to arrays of character objects
Preprocessor Directives
There are some instructions given to the compiler to preprocess the information before the actual compilation begins these instructions are known as preprocessor Directives.
Processor Directives begin with # & don’t end with a semicolon
#define Preprocessor - they are symbolic constants which are known as macros
syntax -
#define macro-name replacement text
- Conditional Compilation - they used to compile the selective portion of the program’s source code using the same directives & like if the selection structure
#ifndef NULL
#define NULL0
#endif
we can compile a program for debugging purposes & can turn ‘debugging’ on or off using a single macro
Macro | Description |
_LINE_ | An integer that gives the current line number of the program when it is being compiled |
_FILE_ | A string that gives the current file name of the program when it is being compiled |
_DATE_ | This command is a string of the form month/day/year that is the data of the translation of the source file into object code |
_TIME_ | This contains a string of the form ‘hour :minute: second’ that is the time at which the program was compiled |
In C++, I/O is done with “streams”
An input stream such as cin is a source of data that can be read into variables.
An output stream such as cout is a place where data can be set for display, storage or communication.
A stream is a sequence of bytes. It is a continuous flow of data elements that are transmitted or intended for transmission in a defined format.
The source stream that provides data to the program is called the input stream.
destination stream that receives output from the program is called output stream
Basic Class Template
The base of the iostream library is the hierarchy of class template
Two types of template parameters → char type(char) & traits
Char type describes the type of elements to be manipulated & traits parameter provides additional characteristics specific to that type of element
class templates have the same name as their char type instantiations but they have the prefix basic in their names
Template instantiation - The act of creating a new definition of a function, class, or member of a class from a template declaration & one or more template arguments is called template instantiation.
- iostream classes use fundamental types on their member’s prototypes
(objects)
|
default char and wchar_t instantiations
|
(new template)
- Types -
streampos → represent positions
streamoff → represent offsets
streamsize → represent sizes
- Manipulators - insertion(<<) & extraction(>>) operators performed on iostream objects
Ex- .endl, .hex, .scientific
We don’t include
<ios>
,<istream>
,<ostream>
,<streambuf>
&<iosfwd>
files directly in the programs as they describe the classes of the hierarchy & are automatically included by other header files of the library that contain derived classes.<iostream> → It contains the declarations of the objects that perform standard input & output operations (including cin & cout).
<fstream> → the file stream class (like the template basic ifstream or the class ofstream)
<sstream> → the classes that are defined in the file manipulate string objects as if they were streams
<iomanip> → Declares some standard manipulators with parameters to be used extraction & insertion operators to modify internal flags & formatting options
Element of the iostream library classes
ios_base → Base class with type-independent members for the standard stream classes.
ios_base → Base class with type-dependent members for the standard stream classes.
istream → Input stream
ostream → Output stream
iostream → Input/Output stream
ifstream → Input file stream
ofstream → Output file stream
ofstream → Input file stream
fstream → Input/Output file stream
istringstream → Input string stream class
ostringstream → Output string stream
filebuf → Base buffer class for streams
stringbuf → Input file stream
stringstream → Input/Output string stream class
- Objects
cin | standard input stream |
cout | standard output stream |
cerr | standard output stream for errors |
clog | standard output stream for logging |
- Types
Focus | stream positive class template |
streamoff | stream offset type |
streampos | stream position type |
streamsize | stream size type |
- Manipulators
Boolalpha | Alphanumerical bool values |
Dec | use decimal base |
Endl | Insert new line and flush. |
Ends | Insert null character |
Fixed | use fixed-point notation |
Flush | Flush Stream buffer |
Hex | use hexadecimal base |
Interval | Adjust the field by inserting, characters at an internal position |
Left | Adjust output to the left |
Noboolalpha | No alphanumerical bool values |
Noshowbase | Do not show numerical base prefixes. |
Noshowpoint | Do not show the decimal point |
Noshowpos | Do not show positive signs |
Noskipws | Do not Skip whitespaces. |
Nounitbuf | Do not force flushes after insertions. |
Nouppercase | Do not generate upper-case letters |
oct | use of octal base |
Resetiosflags | Reset format flags |
Right | Adjust output to the right |
Scientific | Use scientific notation. |
Setbase | Set base field flag |
Setfill | Set fill Character |
Setiosflags | Set format flags |
Setprecision | Set decimal precision |
Set w | set field width |
Showbase | Show numerical base prefixes. |
Shampoint | Show decimal Point |
Showpos | Show positive signs. |
Skipws | Skip whitespaces |
Unitbuf | flush buffer after insertions |
Upper Case | Generate upper-Case letters |
WS | Extract whitespaces. |
Basic Stream Concepts
filestream classes → a stream or array of uninterpreted bytes
- Connecting & Disconnecting streams to file
To connect the ifstream “in_stream” to the file “test.txt”, we use the following statement
in_stream.open("Test.txt");
| | |
Input stream open() fn filename
- Opening input stream
→ in_stream open(Text.txt);
- Closing an input stream
→ in_stream close();
- Opening output stream
→ out_stream open(”Test.txt”);
- closing output stream
→ out_stream close();
#include <fstream> → It must include this file in order to use C++ function for File I/O
ifstream & ostream allows us to declare several classes
Formatted console I/O operations
C++ provides various console I/O functions for formatting the outputs.
Formatting means displaying the outputs in a readable & comprehensible manner
- We can console I/O using two ways
- Using ios class functions & flags
Functions | Task |
width() | It specifies the required field size for displaying an output value |
Precision() | It specifies the no. of digits to be displayed after the decimal point of a float value. |
fill() | It specifies a character that is used to fill the unused portion of a field |
setf() | It specifies the format flags that can control the form of output display(like left justification & right justification) |
unself() | It clears the flags specified |
- Manipulators
Manipulators | equivalent ios function |
setw() | width() |
setprecision() | Precision() |
setfill() | fill() |
setiosflags() | setf() |
resetflags() | unself() |
- Formatting Flags, Bits-field & self()
The value is printed right-justified by default in the field in the field width created when the function width is used
The self() function of the ios class is used to perform to print the text left-justified
syntax -
cout.self(arg1, arg2)
Here, arg1 is the formatting flag defined in the ios class arg2, known as the bit field specifies the group to which the formatting flag belongs
syntax -
cout.self(ios:: left , ios::adjustfield);
cout.self(ios:: scientific, ios::floatfield)
Flags & the bit fields for self() function
Format required | Flag(arg1) | Bit field(arg2) |
Left-justified output | ios::left | ios::adjustfield |
Right-justified output | ios::right | ios::adjustfield |
Padding after sign or base | ios::internal | ios::adjustfield |
scientific notation | ios::scientific | ios::floatfield |
Fixed Point notation | ios::fixed | ios::floatfield |
Decimal base | ios::dec | ios::basefield |
Octal base | ios::oct | ios::basefield |
Hexadecimal base | ios::hex | ios::basefield |
- Displaying trailing zeros & plus sign
The self() function with the flag ios::show point can be used as a single argument to achieve
- Managing Output with Manipulators
Manipulators are the functions that are used to manipulate the output formats & are provided in the header file iomapin.
Manipulator | Meaning | Equivalent |
setw(int w) | set the field width to the width | width() |
setprecision(int d) | set the floating point precision to d | Precision() |
setfill(int c) | set the fill character to c | fill() |
setiosflags (long f) | set the format flag f | setf() |
resetflags (long f) | clear the flag specified | unself() |
endl; | Insert a new line & flush the stream | “\n” |
File Handling is used to store data permanently in a computer, using file handling we can store our data in secondary memory(Hard disk)
The “array” of bytes stored in a file is indexed from zero to len-1, where “len” is the total no. of bytes in the file.
A binary file is a file of any length that holds bytes with values in the range 0 to 0xff (0 to 255).
Steps for achieving file handling:-
step1 - Naming a file
step2 - opening a file
step3 - writing data into the file
step4 - Reading data from the file
step5 - closing a file
- Opening & closing a file → Define a filename using ifstream, ofstream & fstream classes, these classes are contained in the header file fstream.
Two ways to open a file
- Using the constructor function of the class
A constructor initializes an object when it is created
Here for initialization, a filename is used.
Create a file stream object to manage the stream using the appropriate class
To create an input stream, use the ifstream class, and use of ofstream class to create an output stream
i) Open a file for output
ofstream outfile ("results"); // output only the outfile is created as an ofstream object that manages the output Stream.
ii) Open a file for input
ifstream in file("data"); // input only
outfile <<"total";
outfile << "Sum";
infile << number;
infile << String;
//It declares infile as an ifstream biet I attaches it to the dada for reading (input)
For reading & writing the data
i) Individual files for reading & writing the data
Program 1
.....
.....
ofstream outfile ("Salary"); //outfile is created & "Salary" is connected to it.
.....
.....
Program 2
.....
.....
if stream infile ("Salary"); // infile is created & "Salary" is Connect to it
ii) Single files for reading and writing
.....
.....
outfile.close(); // disconnects Salary from outfile & connects to infile
if streaminfile ("Salary");
.....
.....
infile.close();
// disconnect salary form infile.
- Using the member function open() of the class
The open() function can be used to open multiple files that use the same stream object
we want to process a set of files sequentially then we create a single filestream object and use it to open each file in turn.
syntax -
filestream- class stream - object
stream-object.open("filename");
File Mode Parameters
ios::in | Open the file to read |
ios::out | open the file to write |
ios::app | all the date you write is put at the end of the file. it calls ios::out |
ios::ate | all the date you write is put at the end of the file It does not Call ios::out |
ios::trunk | Deletes all previous content in the file (empties the file) |
ios::nocreate | If the file does not exit, opening it with the open() functions gets impossible. |
ios::noreplace | If the file exists, trying to open it with the open() functions, returns an error |
ios::binary | opens the file in binary mode. |
- Checking for failure with file commands
→ File opening was successful or not, notice that there is X, it can be either “o” or “i” or nothing.
- Checking the I/O status - flags
→ I/O system holds info about the result of every I/O operation
→ The current status is kept in an object from type isolate, which is an enumerated type (just like open_mode) defined by ios
- Error-stat-us flags
Goodbit | No errors (no flags set, value = 0) |
Eofbit | The end of the file has been reached |
Failbit | Non-fatal I/O error |
Badbit | Fatal-I/O error |
- To check the I/O status, use the following functions
bool bad(); → the function bad() returns true , if the habit is set
bool bad(); → Read until the end of the file has been reached
bool bad(); → Check if the file opening was successful
bool bad(); → Returns true if there are no errors
- Dealing with Binary Files
Formatted files, sometimes we need to work with unformatted files i.e. binary files
Some Useful Functions :
tellg() → function is used to get the current position of the input pointer in the file. this function returns an integer-type value.
seekp() → function which is used to move the input pointer to a specified location
ignore() → used when reading a file.If you want to ignore a certain number of characters. this function can be used to extract & discord them from the input stream.
getline() → The getline() function is used for the read operation this function can be used to read the contents of the file line by line from an input stream
syntax -
getline(array, array-size, delim);
- peek() → this function will return the type next character from an input file stream, but unlike the function, it won’t move inside the pointer
syntax -
stream_obj.peek();
putback() → It attempts to decrease the correct location in the stream by one character, making the last character extracted from the stream once again available to be extracted by input operations
remove() → The files can be removed by calling the remove function which has the following specification
flush() → whenever you perform a write operation on a file, the contents are not written directly but are saved in a buffer (storage space)
syntax -
stream_obj.flush();
A template can be considered a kind of macro
It can use templates to create a family of classes & functions
It is used to pass data type as a parameter so that we don’t need to write the same code for different data types
Templates are called parameterized classes or function
Implementing a class template :
→ The templates allow us to define generic classes
→ It is a simple process to create a generic class using a template with an anonymous type
→ Templates are expanded at compiler time. this is like macros the difference is, that the compiler does type-checking before template expansion
→ The idea is simple, source code contains only function/class, but compiled code may contain multiple copies of the same function/class
Function Templates
→ A group of functions that are generated from the same template is often called the family of functions
→ In a function template, at least one parameter can stand for any type number of C++ types
- Implementing function templates :
The keyword template
a left angle bracket(<)
a list of generic types, separated with commas if more than one type is needed
a right angle bracket(>)
- The list of generic types has two parts:
The keyword class
An identifier that represents the generic type
syntax :
template<class T>
return type function name (arguments of type T)
{
//body of function with type T whenever appropriate
}
Template Instantiation
- this is a process of creating a specific class from a class template and it is called instantiation, when the compiler generates a class, function or static data members from a template, it is redefined as Template Instantiation.
a class is generated from a class template, it is called a generated class.
a function is generated from a function template, it is called a generated function.
a static data member is generated from a static data member template, it is called a generated static data member.
- Class Template specialization
→ In some cases, it is possible to override the template-generated code by providing special definitions for specific types. this is called template specialization
- Template class partial specialization
It may want to generate a specialization of the class for just one parameter. (a partial specialization matches a given actual list if the template arguments of the partial specialization can be deduced from the actual template arguments list)
Template Function Specialization
In some cases, it is possible to override the template generated Code by providing special definitions for specific types using template specialization.
Static Members and Variables
Each template class or function generated from a template has its copies of any Static variables or members.
Each instantiation of a function template has its Static Variables defined within the scope of the function.
- Template & Friends
With Class templates friendship Can be established between a Class template and a global function, a member function of another Class(possibly a template class), or even an entire class (possible template Class).
syntax :
template <typename T> Class X
The standard template library(STL) is the collection of these generic classes and functions
It is a general-purpose templatized Class & functions that could be used as a Standard approach for the Storing and processing of data.
STL is a C++ library of Container Classes, algorithms and iterators.
It provides many of the basic algorithms and dais Structure of Computer Science.
The STL is a generic library. i.e. its components are heavily parameterized: almost every component of the STL is a template.
Those are many Components present in STL.
Three major Components in STL mainly
Container
Algorithms
iterator
These components work together to provide support for a variety of programming solutions.
The algorithms employ iterators to perform operations stored in containers.
Containers :
The containers are objects that hold data of the same type. It is a way data is organized in memory
The STL containers are implemented by template classes and can be customized to hold many data types.
very many container types are provided by STL which represents objects that contain other objects.
The major ones are sequence containers, associate containers & derived containers
The standard sequence containers include vector, deque & list, Data is stored in a linear sequence in a sequence container
The standard associative containers can be categorized into set, multiset, map and multimap
Associative containers are a generalization of sequences
sequence are indexed by integers
associative containers can be indexed by any type
The derived containers can be classified into three types i.e. stack, queue & priority queue
Iterators :
An iterator is an object(like a pointer) that points to an element in a container.
Iterators can be used to move through the contents of the container
Iterators can handled just like pointers. Iterators can be incremented or decremented
They connect algorithms with containers and play an important role in the manipulation of data stored in the container.
Iterators are like location specifiers for containers or streams of data, in the same way, that an int can be used as a location specifier for any array of integers
an ifstream can be used as a location specifier for a file.
- The STL implements five different types of iterators :
input iterators → which can only be used to write a sequence of values
output iterators → which can only be used to write a sequence of values
Forward iterators → which can be read, written to, and moved forward
Bidirectional iterators → which are like forward iterators but can also move backwards
random access iterators → which can move freely any number of steps in one operation
- Iterators and their characteristics
iterator | Access Method | Direction of movement | I/O capability | Remark |
input | linear | Forward only | Read-only | cannot be saved |
output | linear | Forward only | write-only | cannot be saved |
forward | linear | Forward only | Read/Write | cannot be saved |
bidirectional | linear | Forward & backward | Read/Write | cannot be saved |
random | random | Forward & backward | Read/Write | cannot be saved |
- Algorithms :
Algorithms are functions that can be used across a variety of Containers for processing their contents.
The STL algorithms are template C++ functions to perform operations on Containers
Although each Container provides functions for its basic operators, more than sixty Standard algorithms are provided by STL to support more extended or complex operations
Standard algorithms also allow us to work with two different types of Containers at the same time.
To be able to work with many types of containers, the algorithms do not take contains as arguments.
Instead, they take iterators that specify part or all of a container In this way we can use algorithms to work on entities that are not the Containers as arguments
- The Algorithms include :
Sorting operations (sort, merge, min, max, etc.)
Searching operations (find, count, equal, etc.)
mutating operations (transform, replace, fill , rotate, shuffled)
generalized numeric operations (accumulate, adjacent, difference, etc.)
- Function Objects
the function object is a function that has been wrapped in a class so that it looks like an object.
The class would have only one member function, an overload() operator and no data
This class is templatized to enable its use with different data types.
It is used as arguments for certain Containers & algorithms Ex-
Sort(array, array + 5, greater<int>());
uses the function object greater <int> () to sort the elements. Contained in array in the descending order.
It is useful in Keeping & retrieving state information in functions passed into other functions
- Containers: sequence containers
sequence Containers Store elements in a linear sequence like a line
Each element is related to other elements by its position along the line.
They all expand themselves to allow the insertion of elements, and all of them support several operations.
The 3 types of sequence containers in the STL :
- vector <Type> →
#include<vector>
The vector class is similar to an array. Its syntax is also similar to an array. eg - vector[3]
vector allows random access to the elements, with a constant time overhead of 0(1)
- deque <Type> →
#include<vector>
The double-ended queue, deque (pronounced “deck”) has properties similar to those of a vector
But as you can observe from the name, it is possible to perform insertions & deletions at both ends of a deque
- list <Type> →
#include<vector>
It is not possible with lists to access the elements randomly.
It is best suited for applications in which it is required to add or delete elements to and from the middle.
- Time overhead of operations on sequence containers
Operation | Vector | Deque | List |
Access first element | constant | constant | constant |
Access last element | constant | constant | constant |
Access random element | constant | constant | Linear |
Add/delete at the beginning | Linear | constant | constant |
Add/delete at the end | constant | constant | constant |
Add/delete at random | Linear | Linear | constant |
- Vector, deque, list Functions
Access Functions | Purpose |
begin() | returns iterator pointing to the first element |
end() | returns an iterator pointing after the last element |
push_back(…) | Add an element to the end of the vector |
pop_back(…) | Destroy an element at the end of the vector |
swap(,) | swap two elements |
insert(,) | Insert a new element |
size() | The number of elements in a vector |
capacity() | Element capacity before more money is needed |
empty() | True if the vector is empty |
[] | Random access operator |
- Associate Containers Types -
Set & Multiset - A no. of items can be stored by set and multiset containers & provides operations for manipulating them using the values as keys
Map & Multimap - Map & multimap containers are used to store pairs of items, one called the key & the other called the value.
Exception Handling
The exception handling mechanism aims to identify an exception and take necessary action to handle it.
2 Kinds of exceptions are:
synchronous - Errors like “out of range index” & “overflow” belong to the category of synchronous exceptions
asynchronous - The errors that occur beyond the control of the program (like keyboard interrupts) belong to the category of asynchronous interrupts.
The proposed exception-handling mechanism in C++ is designed to handle only asynchronous exceptions
The exception-handling mechanism suggests a separate error-handling code that performs the following tasks :
Find the problem (hit the exception)
Inform that an error has occurred (throw the exception)
Receive the error information (catch the exception)
Take corrective actions (handle the exception)
- There are 2 parts to error-handling code
one is to detect errors and to throw an exception
The other is to catch the exceptions & to take appropriate actions
Exception Handling Mechanism
Three keywords named try, throw and catch
The block of statements that generate exceptions is preferred by the "try" keyword.
These blocks of Statements are Called "try blocks"
when an exception is detected, it is thrown using a throw Statement in the try block.
A “Catch block" defined by the Keyword "Catch" catches the exception thrown by the throw statement and handlers it appropriately
- The function invoked by try block throwing exception :
Most often, exceptions are thrown by functions that are invoked from within the try blocks
The point at which the throw is executed is called the throw point.
The Control Cannot be returned to the throw point once the exception is thrown to the Catch block.
- Throwing Mechanism → when an exception that is derived to handled is declared, then it is thrown using the “throw” statement
throw(exception);
throw; // it is used for rethrowing an exception
- Catching Mechanism
we include code for handling exceptions in catch blocks
A catch block looks like a function definitions
syntax :
catch (type arg)
{
//statement to manage exceptions
}
- Multiple catch statements
→ Sometimes program segment has more than one condition to then one condition to throw an exception. → In such cases you can associate more than one catch block with a try block.
- User Defined Exception class
→ It is possible to Create your exception class & use them as exception types in your Exception handling Code instead of using predefined data types in C++ as exceptions
- Exception specification
→ It is not necessary to inform the person using your function what exceptions you might throw.
→ However, this is not considered a good practice as he cannot be sure what code to write to catch all potential exceptions.
→ The exception specifications reuse the keyword throw, followed by a parenthesis list of all the potential exception types.
- Unexpected()
→ when something other than what appears in the exception specification is thrown, a special function unexpected() is called.
→ unexpected() is implemented with a pointer to a function , & you can change its behavior
- Set_unexpected()
→ like Set_new_handler(), takes the address of a function with no arguments & void return value
- Catching any exception
→ If your function has no exception specification, any type of exception can be thrown. one solution to this problem is to create a handler that Catches any type of exception. you do this using the ellipses in the argument list
catch()
{
cout<< "an exception was thrown "<<endl;
}
- Rethrowing an Exception
→ Sometimes you may want to rethrow the exception that you just Caught, particularly when you use the ellipses to catch any exception available about the exception.
This is accomplished by saying throw with no argument.
- Standard Exceptions
→ The set of exceptions used with the Standard C++ library is also available for your use. Generally, it's easier & faster to start with a Standard exception class than try to define your own. → If the task which we want to perform cannot be done by the Standard then we should derive from it.
Standard exception
Description | |
Exception | The base class for all the exceptions thrown by the C++ Standard library. you can ask what() & get a result that can be displayed as a character representation |
logic_error | Derived from expression. Reports program logic errors which could presumably be detected before the program executes. |
runtime_error | Derived from exception. Reports runtime errors. which bun presumably be deleted only when the program executes |
- Exceptions derived from logic_error
domain_error | Reports violations of a precondition |
invalid_argument | Indicates an invalid argument to the function it's thrown from. |
length_error | Indicates an attempt to produce an object whose length is greater than or equal to WPOS(largest representable value of type size_t) |
out_of_range | Reports an out-of-range arguments |
Bad_cast | Thrown for executing an invalid dynamic_cast exception in runtime type identification |
Bad_typeid | Reports a null pointer p in an expression typeid (*p) |
- Exceptions derived from runtime_error
range_error | Reports violation of a postcondition. |
overflow_error | Reports an arithmetic overflow. |
bad_alloc | Reports a failure to allocate Storage |
Conclusion
In the end, you will be able to master and write programs in C++ and if you want C++ programs related to its topics go to my GitHub profile I have a repository known as C++ Programs that contains all examples of programs that I explain in this article.
Follow Me On Socials :
Like👍|Share📲|Comment💭