Vous êtes sur la page 1sur 42

Programming paradigm:

Programming paradigm means that the fundamental of computer programming.


Programming style or methods are changed from language to language.
There are three programming paradigm

1. Imperative / Procedural:
Imperative programming languages are the most traditional once. Their code
consists of sequential statements to achieve the desired goal.
For Ex:
Basic and Pascal

2. Functional / Modular:
Functional programming languages are as name suggest, the problems are divided
into functions / modules.
For Ex:
C

3. Object Oriented:
Object oriented programming languages; they mainly focus around objects that
have their own properties and procedural / method.
It is also possible to create classes that include the functionality of other already
existing classes.

Need of OOPs:
Characteristics of OOPs:
i. Emphasis on data rather than procedure.
ii. Programs are divided into what are known as objects.
iii. Function and data are tied together in a data structure.
iv. Data is hidden and cannot be accessed by external functions.
v. Objects may communicate with classes through functions.
vi. New data and functions can be easily added whenever necessary.
vii. Follows bottom up approach in program design.

Some other characteristics included in C++:


a. Ability to declare variable anywhere.
b. New data types like long long int, Boolean and complex data type to denote
complex numbers.
c. New header file such as stdbool.h, inttypes.h.
d. C++ supports exceptional handling for handling errors.
e. C++ introduced new keywords like new, delete, inline, public, private, this etc.
Comparative study of C and C++:
C C++
Designed by Designed by Dennis Ritchie Designed by B. Jarne
Stroustrp
String type Cannot use string type by Can use string type, using
declare it using as an array of string data type
characters
Major Implementations GCC, Borland C, MS VC MSVC++
Program I/O scanf for input or printf for cin for input or cout for
output output
Speed C applications are faster to C++ applications are
compile and execute than generally slower at runtime
C++ applications and are much slower to
compile than C
Program Include Uses #include<stdio.h> Uses #include<iostream.h>
Language type Procedural oriented language Object Oriented language
Influenced awk, C#, objective-C, Pearl, Java, PHP, Pearl, JavaScript,
PHP, Java, C++, JavaScript Ada 95, D
Appeared in 1972 1985
OOP Not built in Yes, polymorphism and
inheritance
Paradigm Procedural system Multi paradigm language
implementation language
Execution flow Top to Bottom Bottom to Top
Principles of Object oriented programming:
Objects:
i. Objects are basic runtime entities in an object oriented system.
ii. In Structured programming problem is divided into function unlike
this, in OOPs the problem is divided into objects.

Diagram

Class:
Language supports different data type like int, float, char, long, structure etc.
Similar to that C++ supports class data type. A class data type contains variable
and functions. They can be accessed through class variables (Objects).
For Ex:
Fruit is a class.
Then mango, orange will be objects of class.

Inheritance:
It is a process by which object of one class acquire the properties of object of
another class. The concept of inheritance provides the idea of reusability. This
means that we can add additional features to an existing class without modifying it.
This is possible by deriving a new class from the existing once.
The new class will have the combined feature of both the classes.

Abstraction:
It is referred to the act of representing essential feature without including
background detail or explanation. Class use the concept of abstraction and are
defined as abstract attributes such as size, weight and cost.
Encapsulation:
The wrapping of data and functions into a single unit (class) is known as
encapsulation.
The data is not accessible to outside world and those functions which are wrapped
into the class can access it.
It is also known as data hiding.

Polymorphism:
It means use one thing in more than one form. Operator overloading & function
overloading are examples of polymorphism.
Function Overloading:
The function name has more than one definition in a class according to arguments
passed to a function.

Operator Overloading:
Uses predefined operators as function name and allow giving it new definition.
Structure of C++ Program:
Include file
Class declaration
Member function definition
Main function

1. Include File:
In this section, we add header files and resource files. These files provide
definition for function and object used in a program.

2. Class Declaration:
In this area class is defined.
Ex:
class demo
{
Member variables and functions
};

3. Member Function Definition:


In this section class member, function and other functions are defined.
Ex:
demo :: fun()
{
Definition
}

4. Main Function:
This is special type of function that is called at the beginning of program
execution. Each program must have one main function.
int main()
{
return 0;
}
Reference Variable:
A reference variable provides an alias (alternative name) for a previously defined
variable.
Syntax:
Data type & reference_name = variable_name;
Ex:
int a=10;
int &b=a;

Comparative study of pointer & reference variable:


i. A pointer can be reassigned any number of time, while a reference variable
cannot be reassigned after initialization.
ii. A pointer can point to NULL but reference variable always point to a value.
iii. We cannot take the address of reference variable like we can do with pointer
variable.

Note: Some other properties of C++


Declaration of variable:
The C++ allows the declaration of variable anywhere in the program.
Dynamic initialization of variable:
Variable can be initialized at runtime using expression at the place of declaration.
Ex:
int sum;
int a=sum;
Memory Management Operators in C++:
To allocate memory, C++ supports two unary operators new and delete. These
operators allocate and deallocate the memory in better and easy way.

Advantages of new operator over malloc function:


i. It automatically computes the size of data object. We need not use the
operator sizeof();
ii. It automatically returns the current pointer type so there is no need to
type cast.
iii. Like any other operator new and delete can be overloaded.
iv. It is possible to initialize the object while allocating the memory.

Syntax for new:


Data type pointer_variable = new data type;
Ex:
int *p = new int;
OR
int *p;
*p = new int;

Note: We can also initialize the memory using new operator.


Pointer_variable = new data type (value);
Ex:
int *p = new int (0);

Note: We can also allocate memory space to array.


Pointer_variable = new data type [size];
Ex:
int *p = new int[5];
Inline Function:
Inline functions definition is placed where it is called in the program. It provides
faster execution by ignoring the function calling process. Member function of class
is defined inline by default. We can define any function as inline using the
keyword inline while defining it.

If following statements written in function body, the inline function may not work

If inline function is recursive.
Loop, switch and goto statement
Static variable
Returning from exit(0) statement
Constructor:
A constructor is a special member function whose task is to initialize the object of
its class. Constructor name is the same as the class name. The constructor is called
whenever an object of its associated class is created.
For Ex:
class integer ()
{
private:
int n, m;
public:
integer ()
{
n=0;
m=0;
}
};

Characteristics of Constructor:
i. They should be declared in public section.
ii. They are called automatically when class objects are declared.
iii. They do not have return type so they cannot return any value.
iv. They cannot be inherited, derived class can call base call constructor.

Types of constructor:
1. Default constructor
2. Parameterized constructor
3. Copy constructor

1. Default constructor:
When a constructor is called without any argument and it is called automatically
when object is created, this is called default constructor.

2. Parameterized constructor:
When a constructor is called with parameters while creating an object; such type of
constructor is called parameterized constructor.
class integer ()
{
private:
int n, m;
public:
integer () //Default
{
n=0;
m=0;
}
integer (int x, int y);
};
integer::integer(int x, int y) //Parameterized
{
n=x;
m=y;
}

3. Copy constructor:
A constructor takes a reference of an object of the same class, itself as an
argument.
A reference variable is used as argument in constructor such a constructor is called
copy constructor.

class emp
{
private:
int id;
public:
emp(int a)
{
id=a;
}
emp(emp &obj)
{
id=obj.id;
}
Void display()
{
cout<<id<<id;
}
};
void main()
{
emp x(100);
emp y(x);
cout<<x;
x.display();
cout<<y;
y.display();
}

Destructor:
A member function that names same as class name preceded by a tilde (~) sign.
Such types of function are called destructor.

class ex
{
static int count;
public:
ex()
{
count++;
cout<<No. of object created<<count;
}
~ex()
{
count--;
cout<<No. of object destroyed<<count;
}

};
void main()
{
ex e1,e2,e3;
{
ex e4;
}
}
Operator Overloading in C++:
It is a special feature of C++. C++ allows operators to be use as function name and
allow user to redefine them with new functionality.
Return_type classname::operator op()
{
statements
}

Unary operator overloading:


When we have an operator that works on single operand such type of overloading
is known as unary operator overloading.
class minus
{
private:
int a,b,c;
public:
void get()
{
cout<<Enter value;
cin>>a>>b>>c;
}

void get()
{
cout<<Minus;
cout<<a<<endl;
cout<<b<<endl;
cout<<c<<endl;
}
void operator -()
{
a=-a;
b=-b;
c=-c;
}
};
Void main()
{
minus m;
m.get();
m.display();
-m; // m.operator-();
m.display();
}

Binary operator overloading:


When we have an operator that works on two operands such type of overloading is
known as binary operator overloading.
class sum
{
private:
Int x,y;
pubic:
sum()
{
x=10;
y=10;
}
void display()
{
cout<<value of x is <<x;
cout<<value of y is <<y;
}
sum operator +(sum obj)
{
Sum t;
t.x=obj.x+x;
t.y=obj.y+y;
return t;
}
};
void main()
{
sum s1,s2,s3;
s1=s2+s3; // s1=s2.operator +(s3);
s1.display();
s2.display();
s3.display();
getch();
}

Note: Operators that cant be overloaded


sizeof, ., .*, ::, ?:

Rules for Operator overloading:


Existing operator can be overloaded new operator cannot be overloaded.
The operator must have at least one operand i.e. a user defined type.
We cannot change the basic meaning of an operator.
Binary operator overloaded through a member function take one argument, those
which are overloaded through a friend function take two argument.
Unary operator overloaded by mean of a member function take no explicit
argument and returns no explicit value.
Those which are overloaded by the means of friend function take one reference
argument.
Friend Class:
A friend class in C++ can access the private and protected members of the class in
which it is declared as friend.
Friend status is not inherited; every friendship has to explicitly declare. Friend
classes can help in improving encapsulation.
A friend class has following characteristics:
1. It allows sharing private and protected member by a non-member function.
2. It provides function with data which is not normally used by the class.

#include<iostream.h>
class csqr;
class crect;
{
int width,height;
public:
int area()
{
area(width*height);
}
void convert(csqr);
};

class csqr
{
int side;
public:
void setvalue(int a)
{
Side=a;
}
friend class crect;
};
void crect::convert(csqr obj)
{
width=obj.side;
height=obj.side;
}
void main()
{
csqr sqr;
crect rect;
sqr.setvalue(10);
rect.convert(sqr);
cout<<rect.area();
}
Operator overloading with friend function:
class array
{
int a[3];
public:
friend ostream & operator<<(ostream &,array &) ;
friend istream & operator>>(istream &,array &) ;
};
ostream & operator<<(ostream &dout,array &obj)
{
for(int i=0;i<3;i++)
dout<<obj.a[i];
return dout;
}
istream & operator>>(istream &din,array &obj)
{
for(int i=0;i<3;i++)
din>>obj.a[i];
return din;
}
void main()
{
array show;
clrscr();
cin>>show;
cout<<show;
getch();
}
Inheritance:
It is process by which object of one class acquire the properties and functionalities
of object of another class.
The class that is predefined is called as base or super class, and the class which use
the existing class is called as derived class or sub class.
The various type of inheritance those are provided by C++ is as follows:
i. Single Inheritance
ii. Multi level Inheritance
iii. Multiple Inheritance
iv. Hierarchical Inheritance
v. Hybrid Inheritance

i. Single Inheritance:
In this, there is only one super class & only one sub class, means they have one to
one communication between them.

ii. Multi level Inheritance:


In this, a derived class can also inherited by another class, means when a derived
class again will be inherited by another class then it create multiple levels of class.
iii. Multiple inheritance:
In this, a class inherits the features of two or more base classes.

iv. Hierarchical Inheritance:


In this, a base class has two or more sub classes or when a base class is used or
inherited by many sub classes, it is called hierarchical inheritance.
v. Hybrid Inheritance:
In this type, it is a mixture of two or more inheritance. A code may contain two or
three types of inheritance in a single call.

Derived
Class OR
Inheritance
type
Base Class Public Protected Private
Public Public Protected Not Inherit
Protected Protected Protected Not Inherit
Private Private Private Not Inherit

class college
{
protected:
char clg_name[10];
public:
void clg_getvalue()
{
cout<<value of college;
cin>>clg_name;
}
};
class dept:public college
{
private:
char dept_name[10];
public:
void dept_getvalue()
{
cout<<value of dept;
cin>>dept_name;
}
void display()
{
cout<<College name <<clg_name;
cout<<Department name <<dept_name;
}
};
void main()
{
dept obj;
clrscr();
obj.clg_getvalue();
obj.dept_getvalue();
obj.display();
getch();
}

Function Overriding:
Redefining a base class function in the derived class to have our own
implementation is referred as overriding.
The signature of the function will be same.

For example:-
Class m
{
public:
void display()
{
cout<<Base class function;
}
};
class n:public m
{
public:
void display()
{
vout<<Derived class function;
}
};
void main()
{
n obj;
obj.display();
obj.show();
obj.m::display();
getch();
}
Constructor in derived class:
The base class contain constructor with one or more parameter, then it is
mandatory for the derived class to have constructor and pass the parameter to the
base class constructor.
In the case of inheritance first base class constructor is called then derived class
constructer is called. In the case of destructor first derived class destructor is called
then base class destructor is called.

class Base
{
public:
Base()
{
cout<<Base class default constructor;
}
Base(int a)
{
cout<<Base class parameterized constructer;
}
~Base()
{
cout<<Base class destructer;
}
};

class Derived:public Base


{
public:
Derived()
{
cout<<Derived class default constructor;
}
Derived(int b):Base(b)
{
cout<<Derived class parameterized constructor;
}
~Derived()
{
cout<<Derived class destructor;
}
};
void main()
{
clrscr();
{
Derived obj(10); // parameterized
}
{
Derived obj1; //Default
}
}
Binding
Static Binding :
The mechanism of linking a function with an object during compile time, is called
early binding or static binding.
The non-virtual member functions are resolved at compile time; this mechanism is
called static binding.
Dynamic Binding :
The mechanism of linking a function with an object at runtime is called late
binding.
The virtual member functions are resolved during runtime; this mechanism is
known as dynamic binding.
Virtual Base Class:
One base class can be inherit by multiple path and derived class may have multiple
copies of base class members, so to inherit one copy of base class we make virtual
inheritance of base class.

class A
{
};
class B: public virtual A
{
};
class C: virtual public A
{
};
class D: public B, public C
{
//one copy of A class is inherited
};
Polymorphism:

Virtual Function:
In the case of inheritance, it makes right function call on the time. When the same
function name is defined in both base and derived class, the function in base class
is declared as virtual using the keyword virtual in the function such a function is
called virtual function.
Ex:

class Base
{
public:
void display()
{
cout<<display base function;
}
virtual void show()
{
cout<<show base function;
}
};

class Derived: public base


{
public:
void display()
{
cout<<display derived function;
}
void show()
{
cout<<show derived function;
}
};

void main()
{
Base *Ptr,b;
Derived d;
Ptr =&b;
Ptr->show();//Base
Ptr->display();//Base
Ptr =&d;
Ptr->show();//Derived
Ptr->display();//Base
}

The rules for virtual function:


I. The virtual function must be member function of some class.
II. They are accessed by using object pointer.
III. A virtual function can be a friend of another class.
IV. We cannot have virtual constructor but we can have virtual
destructor.
V. If a virtual function is defined in the base class, it need not be
necessary redefine in the derived class in such a case, base class function will be
called.
Pure virtual function:
A virtual function that does not have its own body and defined as empty function is
known as pure virtual function.

virtual void function_name()=0;

A pure virtual function is a function declared in a base class that has no definition.
The compiler requires derived class to either define the function or re-declare it.
A class containing pure virtual function cannot be used to declare any object of its
own class.

Abstract Class:
It acts as expression of general concept from which more specific classes can be
derived. We cannot create an object of an abstract class type but we can use pointer
and reference to abstract class type.
A class that contains at least one pure virtual function is called as abstract class.
And classes derived from an abstract class must implement the pure virtual
function.

For ex:

class account
{
private:
int balance;
public:
void getBalance();
virtual void printBalance()=0;
}
Template:
Templates are mechanism that is possible to use one function or class to handle
many different data type by using template.
Template is a feature of C++ programming language that allows function and class
to operate generic function.
Advantages:
i. Template is linked at compile time.
ii. Template reduces the size of code.
iii. Templates are considered type-safe.

Disadvantages:
i. The compiler generates additional code for each template type.

Syntax:
template <class template_var>

Template Function:

We can design a single function that operates on data of many types.

Syntax:
template <class T>
return_type fun_name(argument type T)
{
//Body of function with type T
}

Ex:
template<class T1>
void swap(T1 &x, T1 &y)
{
T1 temp;
temp =x;
x=y;
y=temp;
}
void main()
{
int a=10,b=20;
char x=a, y=z;
float m=10.5, n=20.5;
cout<<After Swap : ;
cout<<\n int a = <<a<< int b = <<b;
cout<<\n char x = <<x<< char y = <<y;
cout<<\n float m = <<m<< float n = <<n;
swap(a,b);
swap(x,y);
swap(m,n);
cout<<Before Swap : ;
cout<<\n int a = <<a<< int b = <<b;
cout<<\n char x = <<x<< char y = <<y;
cout<<\n float m = <<m<< float n = <<n;
getch();
}

Template Function Overloading:


A template function may be overloaded either by template function or ordinary
function.
template <class t1>
void display(t1 x)
{
cout<<Template function<<x;
}
void display(int x)
{
Cout<<Explicit function<<x;
}
void main()
{
display(10);
display(z);
display(10.50);
}
Template Class:

template <class T1, class T2>


class test
{
T1 a;
T2 b;
public:
test(T1 x , T2 y)
{
a=x;
b=y;
}
void show()
{
cout<<a<<and<<b;
}
};

void main()
{
test< float , int > test1 (1.30,123);
test<int , char> test2 (10,w);
test1.show();
test2.show();
getch();
}

A class created from class template is called a template class.

Syntax:
class_name < type > object_name(argument list);
Exception Handling:
Those errors comes in program at run time is known as exception. To manage
these exceptions we create procedure, this is known as exception handling.

Advantages of exception handling:


i. We can trace the error.
ii. It makes error free program.
iii. Exception handling helps to detect program run time error.
Note: This feature of C++ is not supported in Borland Trubo C++

Try Block:
The keyword try contains the block of statements surrounded by braces, which
may generated and this block of statement is known try block.

Catch Block:
This block catch the exception (handle) generated in try block, it is thrown in the
catch block.

Throw statement:
When exception is detected, the throw statement sends the control to catch block.
(The throw statement exists in try block. When throw statement execute, it pass
control to catch block.)

#include <iostream.h>
#include<conio.h>
class Error
{
public:
void devide(int x, int y)
{
If(y!=0)
{
int Result;
Result=x/y;
cout<<Result <<Result;
}
else
{
throw(y);
}
}
};

void main()
{
try
{
Error e1;
e1.divide(10,0);
}
catch(int errr)
{
cout<<Ececution <<err;
}
}

Specifying Exception:
Specifying Exception and multiple catch blocks:
It is possible to restrict a function to throw only specific exceptions. This is done
by specific throw list to function definition.

Note:- If throw statement do not have any list then this function do not throw any
exception.
void test(int x) throw(int, double)
{
if(x==0)
throw x;
else if(x==1)
throw 1;
else if(x==-1)
throw 1.5;
}
void main()
{
Try
{
cout<<Test throw statement;
test(0);
test(1);
test(-1);
}
catch(int i)
{
cout<<Integer exception;
}
catch(char i)
{
cout<<Character exception;
}
catch(double i)
{
cout<<Double exception;
}
}

Rethrow Exception:
When a throw exception generate an exception and transfer the control to outer try
catch block.
void divide(int x,int y)
{
try
{
if(y==0)
{
throw(y);
}
else
{
cout<<Division : x/y;
}
}
catch(int)
{
throw;
}
}
void main()
{
try
{
divide(10,2);
divide(20,0);
}
catch(int)
{
cout<<Exception generate;
}
cout<<End of try catch;
}
File Handling:
Header file used for file handling is fstream.h.
It is a process of storing data into files.
File handling transfers data between program and hard disk file.
C++ has its own function to access file data and store data into files.

Simple program:
void main()
{
char *name; int roll_no;
ofstream fout(data);
fout<<Rahul;
fout<<101;
fout.close();
ifstream fin(data);
fin>>name;
fin>>roll_no;
cout<<roll_no<<name;
fin.close();
}
File Modes:
File modes specify that, how file data will be read and write operation perform.
Mode Description
1. ios::in Open file for read only mode.
2. ios::out Open file for writing mode.
3. ios::app Append data to the end of file.
4. ios::ate Write data on the end of file and provide the
facility of modifying existing contents.
5. ios::binary Create the binary file.
6. ios::nocreate Open fail if file does not exist.
7. ios::noreplace Open fail if file already exist.
8. ios::trunc Delete all the contents of the file if it exists. It
will not create new file.

Note: The mode can combine two or more parameter using the bitwise OR (|).

Input and Output Functions for File handling:


Put and Get function:
i. Put function:
The put function writes a single character to the associated stream/file.
For Ex:
file.put(c)
Writes a character c to the output buffer at the current put position and increases
the put pointer to point the next character.

ii. Get function:


The get function read a single character from the associated stream/file.
For Ex:
file.get(c)
Reads a character c from the current position and increment get pointer to the next
character for next data get.
Sample program for file handling:
#include<iostream.h>
#include<conio.h>
#include<fstream.h>
void main()
{
fstream file;
file.open(data.txt,ios::in|ios::out);
char c[4]={a,b,c,d}, data;
for(int i=0;c[i]!=NULL;i++)
{
file.put(c[i]);
}
file.seekg(0);
cout<<\n Reading data from file\n;
while(file)
{
file.get(data);
cout<<data;
}
file.close();
}
Write and read function:
Write and read functions are specially designed to input or output binary data in
sequence.
file.read((char *)&v, sizeof(v));
file.write((char *)&v,sizeof(v));
file.read(memory_block,size);
file.write(memory_block,size);

Function for manipulating file pointer:


C++ provides some functions that relocate the file pointer and we can set any
position inside the file.

i. seekg():
Move get pointer to specific location.

ii. seekp():
Move put pointer to specific location.

iii. tellg():
Give the current position of get pointer.
iv. tellp():
Give the current position of put pointer.

Examples:
Reference Positions
file.tellp(); 0 ios::beg
file.seekg(offset,reference position); 1 ios::cur
file.seekg(0); 2 ios::end

Error handling in file operation:


Error that may occur
i. A file which we are trying to open for reading does not exist.
ii. The file name used for a new file may already exist.
iii. We may use an invalid file name.
iv. There may not any space in the disk for storing more data.
Error handling functions for file handling
i. eof():
Return true, if end of file (EOF) is detected while reading a file. Otherwise returns
false.
ii. bad():
Return true, if an invalid operation has occurred, otherwise false.
iii. good():
Return true, if no error has occurred, otherwise return fail.
iv. fail():
Return true, when an input or output operation has failed.
STL (Standard Template Library):
STL provide a readymade set of common classes for C++. The STL is general
purpose classes (Data Structure) and function (Algorithm) that could be used as a
standard approach for storing data and processing of data.

Components of STL
1. Containers:
A container is an object that store data. It is a way by which data is organised in
memory. The STL containers are implemented by template class and therefore can
be easily customized.
2. Algorithms:
An algorithm is a procedure that is used to process the data contained in the
container. The STL includes many different kind of algorithm to provide support to
tasks such as initializing, searching, copying, sorting and merging. Algorithms are
implemented by template function.
3. Iterators:
An iterator is an object that point to an element in a container. We can use iterator
to move through the contents of the container. Iterator can handle the data of
container. Iterator connect algorithm with container.

Application of container class


i. Stack
ii. Queue
iii. Vector
iv. DeQue
v. List
vi. Map
vii. Multimap
viii. Priority_Queue