Mastering C++: How to Start Learning Programming

Mastering C++: How to Start Learning Programming

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

LanguagesDeveloperYear of introduced
FORTRANJohn Backus1957
PASCALNiklaus Wirth1970
CDennis Ritchie1973
C++Bjorn Stroutrup1980

Differences in C and C++

ParameterCC++
Programming ParadigmProcedural programming langObject-oriented programming lang
History1972 by Dennis Ritchie1979 by Bjorn Stroutrup
Approachtop-down approachBottom-up approach
Keywords3263
Data Typesbuilt-inbuilt-in & user-defined
File Extension.c.cpp
Header File<studio.h><iostream>
Allocation & Deallocation of memorycalloc() ,malloc() & free()new operator - delete operator
Access ModifierDoes not supportsupport
SecurityNoYes

Functions in the object are known as member functions(Methods).

Basic features of an OOP

  1. Objects - real-world entities, data, functions, methods

  2. Classes - group of object(same property & common)

  3. Inheritance - the process of deriving the properties to another

  4. Polymorphism - the ability to present the same interface in different forms, many forms of a single object

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

  1. Data Types - int, char, float, double

Modifiers - Signed, unsigned, long, short

  1. Variables - container of data, they are names used to refer to memory location

Note - Declare variable before being used

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

  1. Arithmetic Operators(+,-,*,/,%,++ ,--)

  2. Relational Operators(<,>,>=,<=,== ,!=)

  3. Logical Operators(&& , || , !)

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

  1. Documentation Section

  2. Header file Section

  3. Class Declaration or Definition Section

  4. Class Function Definition Section

  5. Main() function Section

Stages in executing a C++ Program

  1. Compiling - the process of converting source code to machine code

  2. Linking - the process of combining the compiled code with libraries and other object files to create an executable program.

  3. 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++ :

  4. 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 ;
  1. Unconditional Statement -

i) break

ii) continue

iii) exit

  • Iteration Statements - loop causes a block of statements to execute repeatedly
  1. for loop
for(initialization ; condition ; increment/decrement)
{
//body of for loop;
statement 1;
statement 2;
}
  1. while loop
while(condition)
{
//body of the while loop
statement 1;
statement 2;
}
  1. 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
  1. Declaration & Definition of arrays

    Ex- int x[10] , x[0] , x[1] to till x[9]

  2. 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:-

  1. Predefined Functions - standard library functions (strcpy , strlen)

  2. User-defined Functions - defined by the user (should be declared before used)

  • Declaration of Functions -
  1. function_name

  2. return_type

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

  1. Pass by value

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

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

  2. External - variable defined outside/external to any functions. reorganized globally, it can used by multiple functions & is automatically initialized to zero.

  3. 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 FunctionMeaningSyntax
strlen()used to find the length of the stringstrlen(string variable)
strrev()used to arrange the characters in reserve order except the null characterstrcpy(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:-

  1. Class is a template that units data and operations

  2. It is an abstraction of real-world entities

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

  1. Private -

  2. Public -

  3. 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 SpecifierSame classoutside classderived class
PublicYesYesYes
PrivateYesNoNo
ProtectedYesNoYes
  • 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 -

  1. Stores the address of the class instance, to enable Pointer access of the members to the member functions of the class.

  2. It is not counted for calculating the size of the object.

  3. Not accessible for static member functions

  4. 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 -
  1. Having the same name as its class, initialize class members when the object of the class is created.

  2. Should be declared in the public section of class for availability to other functions

  3. No return type, not even void.

  4. Cannot be inherited, but the derived class can call the constructor of its baser class.

  5. They call member functions of their class & cannot be virtual

  6. Have default values & can be overloaded.

  7. Can create multiple constructors of the same class but with different parameters

Types of Constructor in C++

  1. 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()
 {

 ....
 }
}
  1. 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)
{
.....;
}
};
  1. 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)
{
.......;
.......;
}
  1. 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

+-*/%^&~
!\=<\>+=-=*=/=%=
^=&==<<\>><< =\>> =\==! =
< =\> =&&++- -,-> *->
()[ ]newnew[]deletedelete[]

Operators that cannot be overloaded

  1. dot operator(.)

  2. The reference pointer to class member ()*

  3. scope resolution operator (::)

  4. size of operator

  5. 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
  1. Create the class for which an operator is to be overloaded.

  2. Declare the functions either as a public or a friend function.

  3. 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 -
  1. overloading function can be either a nonstatic or non-member function with at least one parameter that has a class.

  2. precedence & associativity of the operator cannot be changed.

  3. (Unary, binary, or ternary) is an operator that cannot be changed

  4. Operator - = , [],() & - > can be overloaded only as member functions & not as friend function

  5. Except for assignment operator ‘=’ all the overloaded operators can be inherited by a derived class

  • The benefits of operator overloading are -
  1. Make the program easier to read

  2. Provide the operator with a special meaning for a datatype.

  • Drawbacks of Operator Overloading -
  1. 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.

  1. Conversion from basic to class type

  2. Conversion from class type to basic type

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

  1. Reusability of the code

  2. Time & Efforts are being saved

  3. Improve program structure which can be readable

  4. Easy to Debug

  • Disadvantages of Inheritance in OOPs -
  1. Classes are dependent on each other. i.e. base & superclasses are tightly coupled

  2. The functionality of the base class is changed changed then the changes have to be done on the child classes also.

  3. 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 ClassDerived Class
inherited Public Memberpublic member
inherited Protected memberprotected member
inherited Private numberprivate to base(cannot be accessed)
  • Access Specifier Private -
Base ClassDerived Class
inherited Public Memberprivate member
inherited Protected memberprivate member
inherited Private number(cannot be accessed)
  • Access Specifier Protected -
Base ClassDerived Class
inherited Public Memberprotected member
inherited Protected memberprotected member
inherited Private number(cannot be accessed)

Types of Inheritance

  1. 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;
}
  1. Multiple Inheritance - A class drives from more than one classes

syntax -

class subclassname : access Specifier superlcassname1, superclassname2
{
// class specific code;
}
  1. Hierarchical Inheritance - Here more than one class inherits from a single base class

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

  1. Helps in the reusability of code

  2. Provides easier maintenance of applications

  3. Helps in achieving robustness in applications

Types of Polymorphism -

  1. 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())
{
...
...
}
....
};
  1. 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

MacroDescription
_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 -
  1. streampos → represent positions

  2. streamoff → represent offsets

  3. 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
cinstandard input stream
coutstandard output stream
cerrstandard output stream for errors
clogstandard output stream for logging
  • Types
Focusstream positive class template
streamoffstream offset type
streamposstream position type
streamsizestream size type
  • Manipulators
BoolalphaAlphanumerical bool values
Decuse decimal base
EndlInsert new line and flush.
EndsInsert null character
Fixeduse fixed-point notation
FlushFlush Stream buffer
Hexuse hexadecimal base
IntervalAdjust the field by inserting, characters at an internal position
LeftAdjust output to the left
NoboolalphaNo alphanumerical bool values
NoshowbaseDo not show numerical base prefixes.
NoshowpointDo not show the decimal point
NoshowposDo not show positive signs
NoskipwsDo not Skip whitespaces.
NounitbufDo not force flushes after insertions.
NouppercaseDo not generate upper-case letters
octuse of octal base
ResetiosflagsReset format flags
RightAdjust output to the right
ScientificUse scientific notation.
SetbaseSet base field flag
SetfillSet fill Character
SetiosflagsSet format flags
SetprecisionSet decimal precision
Set wset field width
ShowbaseShow numerical base prefixes.
ShampointShow decimal Point
ShowposShow positive signs.
SkipwsSkip whitespaces
Unitbufflush buffer after insertions
Upper CaseGenerate upper-Case letters
WSExtract 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
  1. Opening input stream

in_stream open(Text.txt);

  1. Closing an input stream

in_stream close();

  1. Opening output stream

out_stream open(”Test.txt”);

  1. 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
  1. Using ios class functions & flags
FunctionsTask
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
  1. Manipulators
Manipulatorsequivalent 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 requiredFlag(arg1)Bit field(arg2)
Left-justified outputios::leftios::adjustfield
Right-justified outputios::rightios::adjustfield
Padding after sign or baseios::internalios::adjustfield
scientific notationios::scientificios::floatfield
Fixed Point notationios::fixedios::floatfield
Decimal baseios::decios::basefield
Octal baseios::octios::basefield
Hexadecimal baseios::hexios::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.

ManipulatorMeaningEquivalent
setw(int w)set the field width to the widthwidth()
setprecision(int d)set the floating point precision to dPrecision()
setfill(int c)set the fill character to cfill()
setiosflags (long f)set the format flag fsetf()
resetflags (long f)clear the flag specifiedunself()
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

  1. 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.
  1. 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::inOpen the file to read
ios::outopen the file to write
ios::appall the date you write is put at the end of the file. it calls ios::out
ios::ateall the date you write is put at the end of the file It does not Call ios::out
ios::trunkDeletes all previous content in the file (empties the file)
ios::nocreateIf the file does not exit, opening it with the open() functions gets impossible.
ios::noreplaceIf the file exists, trying to open it with the open() functions, returns an error
ios::binaryopens 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
GoodbitNo errors (no flags set, value = 0)
EofbitThe end of the file has been reached
FailbitNon-fatal I/O error
BadbitFatal-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 :

  1. tellg() → function is used to get the current position of the input pointer in the file. this function returns an integer-type value.

  2. seekp() → function which is used to move the input pointer to a specified location

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

  4. 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);
  1. 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();
  1. 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

  2. remove() → The files can be removed by calling the remove function which has the following specification

  3. 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 :
  1. The keyword template

  2. a left angle bracket(<)

  3. a list of generic types, separated with commas if more than one type is needed

  4. a right angle bracket(>)

  • The list of generic types has two parts:
  1. The keyword class

  2. 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.
  1. a class is generated from a class template, it is called a generated class.

  2. a function is generated from a function template, it is called a generated function.

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

  1. Each template class or function generated from a template has its copies of any Static variables or members.

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

  1. Container

  2. Algorithms

  3. 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 :

  1. The containers are objects that hold data of the same type. It is a way data is organized in memory

  2. The STL containers are implemented by template classes and can be customized to hold many data types.

  3. very many container types are provided by STL which represents objects that contain other objects.

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

  1. sequence are indexed by integers

  2. associative containers can be indexed by any type

  • The derived containers can be classified into three types i.e. stack, queue & priority queue

  • Iterators :

  1. An iterator is an object(like a pointer) that points to an element in a container.

  2. Iterators can be used to move through the contents of the container

  3. Iterators can handled just like pointers. Iterators can be incremented or decremented

  4. They connect algorithms with containers and play an important role in the manipulation of data stored in the container.

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

  6. an ifstream can be used as a location specifier for a file.

  • The STL implements five different types of iterators :
  1. input iterators which can only be used to write a sequence of values

  2. output iterators which can only be used to write a sequence of values

  3. Forward iterators which can be read, written to, and moved forward

  4. Bidirectional iterators which are like forward iterators but can also move backwards

  5. random access iterators which can move freely any number of steps in one operation

  • Iterators and their characteristics
iteratorAccess MethodDirection of movementI/O capabilityRemark
inputlinearForward onlyRead-onlycannot be saved
outputlinearForward onlywrite-onlycannot be saved
forwardlinearForward onlyRead/Writecannot be saved
bidirectionallinearForward & backwardRead/Writecannot be saved
randomrandomForward & backwardRead/Writecannot be saved
  • Algorithms :
  1. Algorithms are functions that can be used across a variety of Containers for processing their contents.

  2. The STL algorithms are template C++ functions to perform operations on Containers

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

  4. Standard algorithms also allow us to work with two different types of Containers at the same time.

  5. To be able to work with many types of containers, the algorithms do not take contains as arguments.

  6. 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 :
  1. Sorting operations (sort, merge, min, max, etc.)

  2. Searching operations (find, count, equal, etc.)

  3. mutating operations (transform, replace, fill , rotate, shuffled)

  4. generalized numeric operations (accumulate, adjacent, difference, etc.)

  • Function Objects
  1. the function object is a function that has been wrapped in a class so that it looks like an object.

  2. The class would have only one member function, an overload() operator and no data

  3. This class is templatized to enable its use with different data types.

  4. It is used as arguments for certain Containers & algorithms Ex- Sort(array, array + 5, greater<int>());

  5. uses the function object greater <int> () to sort the elements. Contained in array in the descending order.

  6. It is useful in Keeping & retrieving state information in functions passed into other functions

  • Containers: sequence containers
  1. sequence Containers Store elements in a linear sequence like a line

  2. Each element is related to other elements by its position along the line.

  3. 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 :

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

  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

  1. 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
OperationVectorDequeList
Access first elementconstantconstantconstant
Access last elementconstantconstantconstant
Access random elementconstantconstantLinear
Add/delete at the beginningLinearconstantconstant
Add/delete at the endconstantconstantconstant
Add/delete at randomLinearLinearconstant
  • Vector, deque, list Functions
Access FunctionsPurpose
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:

  1. synchronous - Errors like “out of range index” & “overflow” belong to the category of synchronous exceptions

  2. 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 :

  1. Find the problem (hit the exception)

  2. Inform that an error has occurred (throw the exception)

  3. Receive the error information (catch the exception)

  4. Take corrective actions (handle the exception)

  • There are 2 parts to error-handling code
  1. one is to detect errors and to throw an exception

  2. The other is to catch the exceptions & to take appropriate actions

Exception Handling Mechanism

Three keywords named try, throw and catch

  1. The block of statements that generate exceptions is preferred by the "try" keyword.

  2. These blocks of Statements are Called "try blocks"

  3. when an exception is detected, it is thrown using a throw Statement in the try block.

  4. 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 :
  1. Most often, exceptions are thrown by functions that are invoked from within the try blocks

  2. The point at which the throw is executed is called the throw point.

  3. 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
  1. we include code for handling exceptions in catch blocks

  2. 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
ExceptionThe 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_errorDerived from expression. Reports program logic errors which could presumably be detected before the program executes.
runtime_errorDerived from exception. Reports runtime errors. which bun presumably be deleted only when the program executes
  • Exceptions derived from logic_error
domain_errorReports violations of a precondition
invalid_argumentIndicates an invalid argument to the function it's thrown from.
length_errorIndicates an attempt to produce an object whose length is greater than or equal to WPOS(largest representable value of type size_t)
out_of_rangeReports an out-of-range arguments
Bad_castThrown for executing an invalid dynamic_cast exception in runtime type identification
Bad_typeidReports a null pointer p in an expression typeid (*p)
  • Exceptions derived from runtime_error
range_errorReports violation of a postcondition.
overflow_errorReports an arithmetic overflow.
bad_allocReports 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 :

LinkedIn

Twitter

GitHub

Like👍|Share📲|Comment💭

Did you find this article valuable?

Support MOHD NEHAL KHAN by becoming a sponsor. Any amount is appreciated!