History of C++
History of C++
ANSI standards for c++ language says explicit declaration of a function is compulsory
History of C++
C++ was developed by Bjarne Stroustrup at Bell Laboratories over a period starting in 1979
Encapsulation
Data Handling
Abstraction
Polymorphism
Inheritance
iostream.h
We need to include header file iostream.h, it contains declarations for the identifier cout and the operator <<. And also for
the identifier cin and the operator >>.
endl
Inserting endl into the output stream cause the screen cursor to move to the beginning of the next line
Reference Variable
Reference means address
Declaration of Reference variables preceded with ‘&’ symbol (but do not read is as ‘address of’)s
What is Function
Function is block of code performing a unit task.
Function has a name, return type and arguments.
Function is a way to achieve modularization
Functions are Predefined and user-defined
Predefined functions are declared in header files and defined in library files
Declaration
Function Declaration is also known as Function prototype
Function needs to be declared before use (just like variable)
Function can be declared locally or globally
Return Type functionName (argumentList)
Function definition is a block of code
Call by Value
Call by address
Call by reference
Benefits of function
Easy to read
Easy to modify
Avoids rewriting of same code
Easy to debug
Better memory utilization
Function in a program is to save memory space which become appreciable when a function is likely to be called many
times
However, every time a function is called, it takes lot of extra time executing a series of instructions for takes such as
jumping to the function, saving registers, pushing arguments into the stack and returning to the calling function.
So when function is small it is small it is worthless to spend so much extra time in such takes in cost of saving
comparatively small space
Inline function
To eliminate the cost of calls to small functions, C++ proposes a new feature called Inline function
An Inline function is a function that is expanded in line when it is invoked
Compiler replaces the function call with the corresponding function code.
Inline is a request
Inline is a request not a command.
The benefit of speed of inline functions reduce as the function grows in size.
So, the compiler may ignore the request in some situations.
Few of them:
o Function contains loops switch, goto.
o Functions with recursion
o Containing static variable
Default Arguments
A default argument is a value provided in a function declaration that is automatically assigned by the compiler if the calling
function doesn’t provide a value for the argument. In case any value is passed, the default value is overridden.
Function Overloading
How Function Overloading is Resolved
1. Fist C++ tries to find an exact match. This is the case where the actual argument exactly matches the parameter type
of one of the overloaded functions.
2. If no exact match is found, C++ tries to find a match through promotion
o Char, unsigned char, and shot is promoted to an int.
o Float is promoted to double
3. If no promotion is found, C++ tries to find a match through standard conversion
Structure in C++
#include <iostream>
#include<cstring>
struct person{
char name[40];
int age;
char blood_group[3];
};
int main()
person p1;
cout<<"Print"<<endl;
show(p1);
return 0;
person input(){
person p;
cin>>p.name>>p.age>>p.blood_group;
return (p);
cout<<p.name<<endl<<p.age<<endl<<p.blood_group;
}
2nd way using OOPs guidance
#include <iostream>
#include<cstring>
struct person{
char name[40];
int age;
char blood_group[3];
void input(){
cin>>name>>age>>blood_group;
void show(){
cout<<name<<endl<<age<<endl<<blood_group;
};
int main()
person p1;
p1.input();
p1.show();
return 0;
3rd or most best way to store , this you can secure your data jo no one access structure member by using there name
#include<cstring>
struct person{
private:
char name[40];
int age;
char blood_group[3];
public:
void input(){
cin>>name>>age>>blood_group;
void show(){
cout<<name<<endl<<age<<endl<<blood_group;
};
int main()
person p1;
p1.input();
p1.show();
return 0;
1st way to
2nd way
The class
Access specifier
Constructor
As many objects are there will be times print (c1,c2,c3 these are objects).
And object ke bante hi call ho jata hai upper screenshot mai example hai .
IMPORTANT POINTS
A constructor in C++ is a special method that is automatically called when an object of a class is
created.
To create a constructor, use the same name as the class, followed by parentheses ():
If their programmer not created any constructor and try to call it (without parameter) the compiler
not gives error because by default constructor was created and also copy constructor
Copy Constructor
Destructor
Destructor is an instance member function of a class.
The name of the destructor is same as the name of a class but preceded by tilde (`~’) symbol.
Destructor can never be static.
Destructor has no return type.
Destructor takes no argument (No overloading is possible).
It is invoked implicitly when object is going to destroy.
Why destructor?
It should be defined to release resources allocated to an object.
Operator overloading
When an operator is overloaded with multiple jobs, it is known as operator overloading.
It is a way to implement compile time polymorphism.
Rules to Remeber
Any symbol can be used as function name
o If it is a valid operator in C language
o If it is preceded by operator keyword
You can not overload sizeof and ?: operator
1st way is c3=c1.operator+(c2) or 2nd way you can also write like this c3=c1+c2;
For Pre increment do not use argument write like this “class name operator++()”
For post increment use argument write like this “class name operator++(int)”
Friend Function
Friend function can access any member of the class to which it is friend
Friend function cannot access members of the class directly
It has no called object
It should not be defined with membership label
Friend function can become friend to more than one class
o
o If you want all function of class to become another class friend function
then write like this
o
Inheritance
};
Class Derived_Class: Visibility_Mode base_class{
};
Class is used to describe properties and behaviour of an object.
Property names and values
Types of Inheritance
Single Inheritance
Multilevel Inheritance
Multiple Inheritance
Hierarchical Inheritance
Hybrid Inheritance
Visibility Modes
Example:
isme private value inherit hua hai but accessible nhi hai
Is a relationship
Constructor pahle parent class ka run hota hai than child class ka
Assign value in parent class using constructor.
Destructor first child class ka run hota hai than parent class ka
Object Pointer
This pointer
this is a keyword
This is a local object pointer in every instance member function containing
address of called object.
This pointer cannot be modify
It is used to refer called object in member function.
SMA Vs DMA
Method Overriding
It redefines a function of the base class inside the derived class, which
overrides the base class function. Function overriding is an implementation
of the run-time polymorphism. So, it overrides the function at the run-time
of the program
As we know, inheritance is a feature of OOP that allows us to create derived
classes from a base class. The derived classes inherit features of the base
class.
Suppose, the same function is defined in both the derived class and the
based class. Now if we call this function using the object of the derived class,
the function of the derived class is executed.
This is known as function overriding in C++. The function in derived class
overrides the function in base class
Method Overriding
Abstract class
In class, any pure virtual function is present then that class will be called Abstract
class
A class containing pure virtual function is an abstract class
We can not instantiate abstract class
Pure Virtual Function
Template
Template
Function Template
Example: - 👇
Class Template
File Handling
Strems
ifstream = input stream – we use
ifstream when we need to read data
from the file.
ofstream = output stream- we use
ofstream when we need to write data
in the file
fstream:- fstream can do both work
reading and writing both
ios::app :- If you want to add more data on file without erase previous data
then use this.
Text mode vs Binary mode
tellg()
Defined in ostream class
Its prototype is
o -streampos tellg();
Returns the position of the current character in the output stream.
Example of tellg (); – we use tellg with ifstream.
Output
tellp()
Seekg()
We use seekg() to point tellg at any position
Deined in istream class
Its prototype is
o -istream & seekp(streampos pos);
o -istream & seekp(streamoff off, ios_base::seekdir way);
pos is new absolute position within the stream (relative to the beginning).
off is offset value, relative to the way parameter
way value ios_base::beg, ios_base::cur and ios_base::end
Example
Output is
If we use like this fin.seekg(2,ios_base::cur) it mean current position se 2 aage
chale jao Example
Output is:-
seekp();
Initializers
Output of code:
Primitive type to class type can be implemented through constructor
Example: -
Output of code:
Exception Handling
Exceptions
Exception is any abnormal behaviour, run time error.
Exceptions are off beat situation in your program where your program
should be ready to handle it with appropriate response
Exception Handling
C++ provides a built-in error handling mechanism that is called exeption
handling
Using exception handline. You a more easily manage and respond to runtime
errors.
Program statements that you want to monitor for exceptions are contained
in a try block.
If any exception occurs within the try block, it is thrown (using throw).
The exception is caught, using catch, and processed
Simple Example
Output of code:
Output of code:
Catch
When an exception is caught, arg will receive its value.
If you don’t need access to the exception itself, specify only type in the catch
clasuse-arg is optional.
Any type of data can be caught, including classes that you create.
Throw
Dynamic Constructor
Output of code:
Accessing members of namespace
using keyword allows you to import an entire namespace into your program
with a global scope
It can be used to import a namespace into another namespace or any
program
Nested Class
Nested class
Introduction to STL
Containers
Algorithms
Algorithms act on containers. They provide the means by which you will
perform initialization, sorting, searching, and transforming of the contents of
containers.
Algorithms library contains built in function that performs complex
algorithms on the data structures
Iterators
STL Containers
Containers
Common Containers
Classification of Containers
Array
Member functions
Following are the important and most used member function of array
template
at: -
o This method returns value in the array at given range
o If the given range is greater than the array size.out_of_range exception is
thrown
Example: -
Output of code:
[] operator
o The use of operator [] is same as it was for normal arrays
o Example: -
Output of code:
front()
o front() method returns the first element in the array
o Example: -
Output of code:
back()
o back() method returns the last element in the array
o Example: -
Output of code:
fill()
o This method assign the given value to every element of the array
o Example: -
Output of code:
swap()
o This method swaps the content of two arrays of same type and same
size
o It swaps index wise, thus element of index I of first array will be
swapped with the element of index i of the second array
o first_array.swap(second_array)
o Example: -
Output of code:
size()
o This, method returns the number of elements present in the array
o Example: -
Output of code:
begin()
o begin() method returns the iterator pointing to the first element of the
array
end()
o end() method returns an iterator pointing an element next to the last
element in the array
Pair in STL
pair<T1,T2>pair1;
Example:
o pair <string, int>p1;
Inserting Value
p1=make_pair(“Suraj”,16);
pair<string,int>p1;
p1=make_par(“Suraj”,19);
cout<<p1.first<<endl;
cout<<p1.second<<endl;
Example: -
Output of code:
Example: -
Output of code:
Tuple in STL
Just like in pair, we can pair two heterogeneous objects, in tuple we can pair
multiple object
Inserting Value
t1=make_tuple<”India”,16,10);
Example: -
Output of code:
Vector
Output of code:
Vector Size
vector<string>V{“Suraj”,”Patel”};
Subscript operator []
push_back()
push_back() is a member function, which can be used to add value to the vector
at the end
Example: -
Output of code:
pop_back()
capacity()
size()
Output of code:
clear()
Output of code:
at()
Output of code:
Iterator
list<int>l1;
list<int>l2 {11,22,33,44};
list<string>l3{“Dellhi”,”Lucknow”,”Dhaka” }
Printing a list
Example: -
Output of code:
size()
It tells the how many elements in the list Example: -
Output of code:
Output of code:
sort()
This function sort the list Example: -
Output of code:
reverse()
reverse function reverse the list of element. Example: -
Output of code:
remove ()
remove function is used to remove particular elment in the list Example: -
Output of code:
clear ()
clear function removes all element of the list Example: -
Output of code:
map class in STL
map
Map property
Example: -
How to print map
Output of code:
Useful functions of map class
at()
at function print particular index value Example:
Output of code:
square []
Same like at if you want print particular index value Example: -
Output of code:
size()
size function tells the how many element there Example: -
Output of code: -
empty()
empty function tell that the map is empty or not If empty than print 1 if not
then print 0 example: -
Output of code:
insert()
Insert function use to insert data Example: -
Output of code:
clear()
remove all the element of the map example: -
Output of code:
String class
Careless programmer can overrun the end of an array that holds a null
terminated string
For example, using strcpy()
String class handles such issues
string is in STL
Constructors
Operators
Insertion and extraction
Mixed operations
You can mix string object with another string object or c style string
C++ string can also be concatenated with character constant
Example: -
Output of code:
Useful methods
assign()
assign function assign value in the variable Example: -
Output of code:
append()
append function like concatenated Example: -
Output of code:
insert()
This function is used to insert a new character, before the character
indicated by the position pos. Example:-
Output of code:
replace()
replace function use to replace example: -
Output of code:
erase()
erase function removes all data from the variable Example: -
Output of code:
rfind()
similar like find but it search from back if there is two similar word than it
count second word index and tell Example: -
Output of code:
compare ()
it compares two strings
o If answer is 0 than it means both strings have same string
o If answer is 1 or -1 it means both string is different
Example: -
Output of code:
c_str()
c str is used to string copy in the array Example: -
Output of code:
size()
it tells the length of the string Example: -
Output of code: