C++ Notes For Ignou Students
C++ Notes For Ignou Students
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.
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
};
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;
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
}
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();
}
#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.
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 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;
}
};
void main()
{
Base *Ptr,b;
Derived d;
Ptr =&b;
Ptr->show();//Base
Ptr->display();//Base
Ptr =&d;
Ptr->show();//Derived
Ptr->display();//Base
}
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:
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();
}
void main()
{
test< float , int > test1 (1.30,123);
test<int , char> test2 (10,w);
test1.show();
test2.show();
getch();
}
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.
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 (|).
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
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.