NOTES
NOTES
NOTES
Programming
Index
Chapter 1. Object Oriented Programming
Chapter 2. Introduction To CPP
Chapter 3. Classes & Objects
Chapter 4. Functions In CPP
Chapter 5. Constructor & Destructor
Chapter 6. Inheritance
Chapter 7. Virtual Functions
Chapter 8. Operator Overloading & Type Conversion
Chapter 9. Introduction To C++ I/O System
Chapter 10. Exception Handling
Chapter 11. Templates
Chapter 12. File Handling
Chapter No. 1
Object Oriented Programming
Software Evolution
OOPS Concepts
Dalcomp Technologies 3
Software Evolution
1,0 Binary
Machine Language
Assembly Language
functions.
Dalcomp Technologies 5
Characteristics of Procedure Oriented
Programming
Dalcomp Technologies 6
Characteristics of Object Oriented
Programming
Emphasis is on data rather than procedure.
objects.
Dalcomp Technologies 7
Characteristics of Object Oriented
Programming
Data is hidden & cannot be accessed by external functions.
Dalcomp Technologies 8
OOPs Concepts
Object :-
1. Objects are the basic run time entities in an object oriented
system.
2. They may represent a person, a place, a table, a bank account, a
table of data or any item that the program has to handle.
3. For ex:- If “Customer” & “Account” are two objects in a
program, then the customer object may send a msg to the acct
object requesting for the bank balance.
Dalcomp Technologies 9
Class :-
1. We just mentioned that objects contain data, & code to
manipulate that data, the entire set of data & code of an
object can be made a user defined data type with the
help of a Class.
2. For Ex.
Mango, Apple & Orange are the members of class
fruit.
3. If the fruit has been defined as a class , then the
statement
fruit mango;
will create an object mango belonging to the class fruit.
Dalcomp Technologies 10
Data Abstraction :-
details.
2. The data is not accessible to the outside world & only those
functions which are bind inside the class can access it.
Dalcomp Technologies 13
4. Writing data and code into the single unit class is known as
Data Hiding .
layer & another drug is stored in upper layer these 2 layers are
Dalcomp Technologies 14
Polymorphism:-
1. Polymorphism means “many forms and one interface”.
2. It allows us to have many function with the same name inside a
class.
Polymorphism
Virtual
Operator Function Functions
Overloading Overloading
e.g. cin>>n; e.g. int add(int, int);
C = a>>2; Float add(float, int);
For Ex:- A man can be a Father, Son ,Husband, Employee & Good Citizen.
15
Inheritance:-
Inheritance(Extending class)
Marks
Sub 1, Sub 2 Derived Class Data Members
get() , put() Derived Class Methods
Dalcomp Technologies 16
Dynamic Binding:-
Shape
Draw()
4. For Ex. In the given figure, for draw() method ,at run time, the
code matching the object under current reference will be called.
Dalcomp Technologies 17
Message Passing:-
For Ex:-
Employee.Salary(name);
Object Information
Message
Dalcomp Technologies 18
Benefits Or Advantages of OOPS
1. Through inheritance, we can eliminate redundant code & extend the use of
existing classes.
2. We can build programs from the standard working modules that communicate
with one another rather than having to start writing the code from scratch. This
3. The principle of data hiding helps the programmer to build secure programs
Dalcomp Technologies 19
4. It is possible to have multiple instances of an object to co-
to large systems.
much simpler.
Home
Dalcomp Technologies 21
Chapter No. 2
Introduction To C++
Introduction
Difference between C & C++
First Program of C++
Introduction to Classes
Scope Resolution Operator
Memory Management Operator
Difference between dynamic memory allocation in C & C++
Reference Variable
Dalcomp Technologies 22
Introduction
Dalcomp Technologies 23
Difference Between C & C++
1. C follows the procedural programming paradigm while C++ is a multi
paradigm language(procedural as well as object oriented)
Dalcomp Technologies 24
Difference Between C & C++
3. C is regarded as a low-level language(difficult interpretation &
less user friendly) while C++ has features of both low-
level(concentration on whats going on in the machine
hardware) & high-level languages(concentration on the
program itself) & hence is regarded as a middle-level
language.
4. C uses the top-down approach while C++ uses the bottom-up
approach
Dalcomp Technologies 26
First program of c++
Dalcomp Technologies 27
Scope Resolution Operator
This Operator is used for:-
void test :: getdata()
1. To unhide the global variable that
{
might have bought hidden by
local variables. x=10;y=20;
2. To access members declared in }
class scope. void main()
{
For Ex:- class test test s;
{ s.getdata();
int x,y; s.disp();
public: void getdata(); getch();
void disp() }
{
Output:-
cout<<x<<“\t”<<y;
} 10 20
};
Dalcomp Technologies 28
Example of Scope Resolution Operator to access global variables:-
#include<iostream.h>
void main()
{
int m =20; // m local to main
Output:-
{ We are in inner block
int k = m; k = 20
int m = 30; // m declared again m= 30
::m = 10
cout<<“We are in inner block\n”; We are in outer block
cout<<“k=“<<k<<“\n”; m = 20
cout<<“m=”<<m<<“\n”; ::m = 10
cout<<“::m=” << ::m << “\n”;
}
cout<<“n We are in outer block \n”;
cout<<“m=”<<m<<“\n”;
cout<<“::m=“ << ::m<<“\n”;
getch();
Dalcomp Technologies 29
}
Memory Management Operator
C++ Provides two operators for dynamic memory allocation &
deallocation:-
Dalcomp Technologies 30
2)delete operator :- When the memory allocated dynamically is
delete operator.
Dalcomp Technologies 31
Difference between memory management in c & c++
Memory management in C Memory management in C++
1. Dynamic memory management is 1. Dynamic memory management is
done using function like done using operators new &
malloc(),calloc,realloc & free. delete.
2. Fuctions require additional time. 2. Operators execute faster.
3. We have to include header file to 3. No need of any header file.
use this function.
4. The allocated memory can be
4. The allocated memory can only initialize to any value.
be initialize to 0.
5. The operators can be overloaded
5. This functions can not be in c++.
overloaded in c.
Dalcomp Technologies 32
Reference Variables
Dalcomp Technologies 33
Reference Variables
Dalcomp Technologies 34
Example of reference variable
#include<iostream.h>
void main()
{
int x= 10;
clrscr();
cout<<“Value of x:”<<x;
int &rx = x; // reference variable
Value of x: 10
cout<<“Value of x:”<<rx; Value of x: 10
rx = rx + 5; Value of x: 15
cout<<“Value of x:”<<x;
getch();
}
Dalcomp Technologies 35
End Of Chapter 2
Any Question?
Home
Dalcomp Technologies 36
Chapter No. 3
Classes And Objects
Declaration & Syntax Of Class & Object
Access Specifiers In Class
Creating Object
Defining Member Functions
Private Member Function
Arrays Within a Class
Static Class Members
Friend Functions
Dalcomp Technologies 37
Definition & Syntax of Class & Object
A class is an expanded concept of a data structure: instead of
Classes are generally declared using the keyword class, with the
following format:
Dalcomp Technologies 38
class class_name
{
access_specifier_1 :
data type variable_name ;
access_specifier_2 :
data type member2;
access _specifier
data type method name(){ } ;
...
} object_names;
Dalcomp Technologies 39
Example of Class
#include <iostream>
class CRectangle {
int x, y; //data member or data variables
public:
void set_values (int,int); // member functions
int area () {return (x*y);}
};
void CRectangle::set_values (int a, int b) {
x = a;
y = b;
}
int main () {
CRectangle rect; //obj declaration
rect.set_values (3,4);
cout << "area: " << rect.area();
Area : 12
return 0;
}
Dalcomp Technologies 40
Creating Object
Dalcomp Technologies 41
Defining Member Functions
1. Outside The Class Definition
2. Inside The Class Definition
1. Outside Class Definition:-
Syntax:
return_type class_name::fun_name(arg_declaration)
{
Function Body;
}
Dalcomp Technologies 42
Access Specifiers
private members of a class are accessible only from within other
members of the same class or from their friends.
Dalcomp Technologies 43
Defining Member Functions
2. Inside The Class Definition
Syntax:- return_type function_name(arg.decln)
{
function body;
}
Dalcomp Technologies 44
Example of Defining Member Function Outside
class Box
double Box::getVolume(void)
{
{return length * breadth * height; }
public: double length;
};
Dalcomp Technologies 45
void Box::setHeight( double hei )
volume = Box1.getVolume();
{ height = hei; }
cout << "Volume of Box1 : " << volume
int main( )
Box2.setHeight(10.0);
Dalcomp Technologies 46
Example Of Defining Member Function
Inside
class item void main()
{ {
int number; item x;
float cost; cout<<“Item x:”<<“\n”;
public:
void getdata(int a,int b) x.getdata(100,299.95);
{number = a; cost = b;} x.putdata();
void putdata(void) getch();
}
{
cout<<number;
Item x:
cout<<cost; 100
} 299.95
};
Dalcomp Technologies 47
Member function have some special
characteristics
Several different classes can use the same function name. The
‘membership label’ will resolve their scope.
Dalcomp Technologies 48
Making an outside function inline
Dalcomp Technologies 49
Inline Function
C++ inline function is powerful concept that is commonly used with classes.
If a function is inline, the compiler places a copy of the code of that function
To inline a function, place the keyword inline before the function name and
define the function before any calls are made to the function. The compiler
can ignore the inline qualifier in case defined function is more than a line.
Dalcomp Technologies 50
Example Of Making An Outside Function Inline
Example:
class item
{
......
......
public:
void getdata(int a,float b);
};
inline void item :: getdata(int a,float b)
{
number=a;
cost=b;
}
Dalcomp Technologies 51
Example Of Inline Function :-
#include<iostream.h>
class line
{
public:
inline float mul(float x,float y)
{
return(x*y);
}
inline float cube(float x)
{
return(x*x*x);
}
};
Dalcomp Technologies 52
void main()
{ line obj;
float val1,val2;
clrscr();
cout<<"Enter two values:";
cin>>val1>>val2;
cout<<"\nMultiplication value is:"<<obj.mul(val1,val2);
cout<<"\n\nCube value is :"<<obj.cube(val1)<<"\t"<<obj.cube(val2);
getch();
} Output:
Enter two values: 5 7
Multiplication Value is: 35
Cube Value is: 25 and 343
Dalcomp Technologies 53
Private Member Functions
Public:
The private member function are not
void show()
directly accessible outside the class, {
we can access them in public disp();
member function of same class & cout<<“show”;
that function is accessible outside the }
};
class.
void main()
{
Class test
{ test s;
void disp() s.show();
{ getch(); display show
cout<<“display”; }
}
Dalcomp Technologies 54
Arrays within a class
The arrays can be used as member variables in a class. The
following class definition is valid.
Class array
{
int a[size]; // a is int type array
public:
void setval(void);
void display(void);
};
Dalcomp Technologies 55
Example Of Arrays within Class:-
#include<iostream.h>
class items
{
int itemCode[m];
float itemPrice[m];
int count;
public:
void CNT(void){
count = 0;
} //initializes count to 0
void getitem(void);
void displaySum(void);
void remove(void);
void displayItems(void);
};Dalcomp Technologies 56
void items :: getitem(void) // assign values to data
{
cout<<“Enter item code:”;
cin>>itemCode[count];
cout<<“Enter item cost:”;
cin>>itemPrice[count];
count++;
}
void items :: displaySum(void) //display total value of all items
{
float sum = 0;
for(int i=0;i<count;i++)
sum = sum + itemPrice[i];
cout<<“\n Total value:”<<sum<<“\n”;
Dalcomp Technologies 57
}
void items :: remove(void) //delete a specified item
{
int a;
cout<<“Enter item code:”;
cin>>a;
for(int i=0;i<count;i++)
if(itemCode[i] == a)
itemPrice[i] = 0;
}
Dalcomp Technologies 58
int main()
{
items order;
order.CNT();
int x;
do // do…….while loop
{
cin >> x;
Dalcomp Technologies 59
switch(x)
{
case 1: order.getitem();break;
case 2: order.displaySum();break;
case 3: order.remove();break;
case 4: order.displayItems(); break;
case 5: break;
default : cout <<“Error in input; try again\n”;
}
} while (x != 5); //do … while ends
return 0;
}
Dalcomp Technologies 60
Output:
You can do the following : Enter appropriate number
1 : Add an item
2 : Display total value
3 : Delete an item
4 : Display all items
5 : Quit
What is your option? 1
Enter item code : 111
Enter item cost : 100
Dalcomp Technologies 62
You can do the following : Enter appropriate number
1 : Add an item
2 : Display total value
3 : Delete an item
4 : Display all items
5 : Quit
What is your option? 3
Enter item code : 222
Dalcomp Technologies 64
Static Class Members
Dalcomp Technologies 65
Example of Static Data Member
Class test
{
public:
static int a;
void disp()
{cout<<“\n\t”<<a;}
};
int test :: a=10;
void main()
{
test s1;
S1.disp();
Output: 10
test s2;
s2.disp();
10
getch();
}
Dalcomp Technologies 66
Another Example Static Data Members:-
#include<iostream.h>
class item
{ a.getcount();
static int count; b.getcount();
int number; c.getcount();
Public:
void getdata(int a) a.getdata(100);
{ b.getdata(200);
number = a; c.getdata(300);
count++;
} cout<<“After reading data”<<“\n”;
void getcount(void)
{ a.getcount();
count : 0
cout<<“Count:”; b.getcount();
c.getcount(); count : 0
cout<<count<<“\n”;
count : 0
}
getch(); After reading data
};
int item :: count;
} Count : 3
Count : 3
void main()
Count : 3
{
item a,b,c;
Dalcomp Technologies 67
Static Class Members
Static Member Functions:-
A static member function can have access to only other static
members declared in the same class.
Class_name :: function_name;
Dalcomp Technologies 68
Example of Static Member Function
Class test
{
public:
static void disp()
{ cout<<“display”;}
};
void main()
{
clrscr();
display
test :: disp();
getch();
}
Dalcomp Technologies 69
Another Example of Static Member Functions:-
#include<iostream.h>
Class test
{
int code;
static int count;
public :
void setcode (void)
{
code = ++count;
}
void showcode(void)
{
cout<<“Object number:”<<code<<“\n”;
}
static void showcount(void)
{
cout<<“count:” <<count<<“\n”;
}
};
Dalcomp Technologies 70
int test :: count;
int main()
{
test t1,t2;
t1.setcode();
t2.setcode();
Count : 2
test :: showcount();
Count : 3
Object number:1
test t3; Object number:2
t3.setcode(); Object number:3
test :: showcount();
t1.showcode();
t2.showcode();
t3.showcode();
return 0;
} Dalcomp Technologies 71
Friend Functions
The private members cannot be accessed from outside the class. i.e. a
non-member function cannot have an access to the private data of a
class.
Dalcomp Technologies 72
Characteristics of friend function:-
friend.
Since it is not in the scope of the class, it cannot be called using the
object.
Dalcomp Technologies 73
Characteristics of friend function:-
directly & has to use an object name & dot membership operator
It can be declared either in the public or the private part of a class
Dalcomp Technologies 74
Example of friend function
class sample
{
int a;
int b;
public:
void setvalue()
{ a = 25; b = 40 ; }
friend float mean(sample s);
};
Float mean(sample s)
{
return float(s.a + s.b) / 2.0;
}
Dalcomp Technologies 75
Example of friend function
void main()
{
sample x;
x.setvalue();
cout<<“Mean value =” <<mean(x)<<“\ns”;
}
Output : Mean
Value = 32.5
Dalcomp Technologies 76
A Function Friendly to two classes
#include<iostream.h>
class ABC;
class XYZ
{
int x;
public:
void setvalue(int i) { x = i ;}
friend void max(XYZ,ABC);
};
Class ABC
{
int a;
public:
void setvalue(int i){a = i;}
friend void max(XYZ,ABC);
};
Dalcomp Technologies 77
void max(XYZ m,ABC n)
{
if(m.x>=n.a)
cout<<m.x;
else
cout<<n.a;
}
int main() 20
{
ABC abc;
abc.setvalue(10);
XYZ xyz;
xyz.setvalue(20);
max(xyz,abc); //friend function called as normal function
return 0 ;
}
Dalcomp Technologies 78
Returning Objects
A Function cannot only receive objects as arguments but also can return them.
The example illustrates how an object can be created (within a function) and
returned to another function.
#include<iostream.h>
class complex // x+iy form
{
float x; // real part
float y; // imaginary part
public:
void input(float real, float imag)
{ x = real; y = imag; }
friend complex sum(complex, complex);
void show (complex);
};
Dalcomp Technologies 79
complex sum(complex c1, complex c2) int main()
{ {
complex c3; //object c3 is created complex A,B,C;
c3.x = c1.x + c2.x; A.input(3.1,5.65);
B.input(2.75,1.2);
c3.y = c1.y + c2.y;
c = sum(A,B); // C = A + B
return (c3); // returns object c3 cout<<“A = “; A.show(A);
} cout<<“B = “; B.show(B);
void complex :: show(complex c) cout<<“C= “; C.show(c);
{ return (0);
}
cout<<c.x<<“+j”<<c.y<<“\n”;
}
}
A = 3.1 + j5.65
B = 2.75 + j1.2
C = 5.85 + j6.85
Dalcomp Technologies 80
End Of Chapter 3
Any Question?
Home
Dalcomp Technologies 81
Chapter No. 4
Functions In C++
Introduction To Function
Advantages Of Function
Function Call Methods
Remarks on Functions
Local vs Global Variables
Function Overloading
Inline Function
Dalcomp Technologies 82
Introduction To Function
Dalcomp Technologies 83
Introduction To Function
Dalcomp Technologies 84
Advantages Of Functions
Dalcomp Technologies 85
Function Call Methods
Call by value
Call by reference
Dalcomp Technologies 86
Function Call Methods
Call by value
Up to this point all the calls we have seen are call-by-value, a copy of the value
(known) is passed from the caller-function to the called-function
Any change to the copy does not affect the original value in the caller function
Call By Reference
We introduce reference-parameter, to perform call by reference. The caller
gives the called function the ability to directly access the caller’s value, and to
modify it.
A reference parameter is an alias for it’s corresponding argument, it is stated
in c++ by “flow the parameter’s type” in the function prototype by an
ampersand(&) also in the function definition-header.
Advantage: performance issue
87 Dalcomp Technologies
Function Call Methods
void function_name (type &);// prototype
main()
{
-----
------
}
void function_name(type *parameter_name)
88 Dalcomp Technologies
Function Call Example
passing parameters by reference:
#include <iostream>
using namespace std;
int main ()
{ x=2, y=6, z=14
int x=1, y=3, z=7;
duplicate (x, y, z);
cout << "x=" << x << ", y=" << y << ", z=" << z;
return 0;
}
89 Dalcomp Technologies
compute square and cube of numbers [1..10] using functions
#include<iostream.h>
// number1, number2 and number3 are arguments to the maximum function call
cout << "Maximum is: " << maximum( number1, number2, number3 ) << endl;
return 0;
}
// function maximum definition. x, y and z are parameters
double maximum( double x, double y, double z )
{ Enter three real numbers: 99.32
double max = x; // assume x is largest 37.3 27.1928
if ( y > max ) // if y is larger,
max = y; // assign y to max
Maximum is: 99.32
if ( z > max ) // if z is larger,
max = z; // assign z to max
Enter three real numbers: 1.1
return max; // max is largest value 3.333 2.22
Dalcomp Technologies
} Maximum is: 3.333 91
void Function takes arguments
If the Function does not RETURN result, it is called void Function
#include<iostream.h>
void add2Nums(int,int);
main()
{ int a, b;
cout<<“Enter two Number:”;
cin >>a >> b;
add2Nums(a, b) Enter two Number:
return 0; 3 5
} 3+5 = 8
void add2Nums(int x, int y)
{
cout<< x<< “+” << y << “=“ << x+y;
}
92 Dalcomp Technologies
void Function take no arguments
If the function Does Not Take Arguments specify this with EMPTY-LIST OR write
void inside
#include<iostream.h>
void funA();
void funB(void)
main()
{
funA(); Will be the same
funB(); in all cases
return 0;
}
void funA()
{
cout << “Function-A takes no arquments\n”;
}
void funB()
{
cout << “Also Function-B takes No arguments\n”;
}
93 Dalcomp Technologies
Remarks on Functions
Local variables
o Known only in the function in which they are defined
o All variables declared inside a function are local variables
Parameters
o Local variables passed to function when called ( passing-
parameters)
Variables defined outside and before function main:
o Called global variables
o Can be accessible and used anywhere in the entire program
94 Dalcomp Technologies
Local vs Global Variables
#include<iostream.h>
int x,y; //Global Variables
int add2(int, int); //prototype
main()
{ int s;
x = 11;
y = 22;
cout << “global x=” << x << endl;
cout << “global y=” << y << endl;
s = add2(x, y);
cout << x << “+” << y << “=“ << s;
cout<<endl;
return 0;
} global x=11
int add2(int x1,int y1) global y=22
{ int x; //local variables Local x=44
x=44; 11+22=33
cout << “\nLocal x=” << x << endl;
return x1+y1;
}
95 Dalcomp Technologies
Function Overloading
Function overloading
Dalcomp Technologies 96
Example Of Function Overloading
#define pi 3.14
class fn
{
public:
void area(int); //circle
void area(int,int); //rectangle
void area(float ,int,int); //triangle
};
void fn::area(int a)
{
cout<<"Area of Circle:"<<pi*a*a;
}
Dalcomp Technologies 97
void fn::area(int a,int b)
{
cout<<"Area of rectangle:"<<a*b;
}
void fn::area(float t,int a,int b)
{
cout<<"Area of triangle:"<<t*a*b;
}
void main()
{
int ch;
int a,b,r;
clrscr();
fn obj;
cout<<"\n\t\tFunction Overloading";
1. Area of Circle
2. Area of Rectangle
3. Area of Triangle
4. Exit
Enter Your Choice: 4
Home
Dalcomp Technologies 101
Chapter 5
Constructors & Destructors
Introduction To Constructor
Types Of Constructor
o Default Constructor
o Parameterized Constructor
o Copy Constructor
Constructor Overloading
Destructor
No Return Values.
Default Constructor
Parameterized Constructor
Copy Constructor
Dynamic Constructor
Member-Variables
Member-Functions
public:
class-name()
// Constructor code
}
... other Variables & Functions
}
Dalcomp Technologies 105
Example Of Default Constructor
class Example int main()
{ {
int a,b; Example Object;
public: //Constructor
Example() // Constructor invoked.
{
Object.Display();
a=10;
b=20; return;
cout<<"Im }
Constructor"
}
Member-Variables
Member-Functions
public:
#include<iostream.h>
class integer
{
int m,n;
Public:
integer (int,int); constructor declared
void display(void)
{
cout<<“m = ”<< m << “\n”;
cout<<“n = ”<<n<<“\n”;
}
};
integer :: integer (int x,int y) constructor defined
{
m = x; n = y;
}
cout<<“\n Object2”<<“\n”;
int2.display();
Output:
Object1
return 0; m=0
} n = 100
Object2
m = 25
n = 75
If I 1 and I 2 are objects, this statement is legal and assigns the
values of I 1 to I 2, member-by-member.
return 0;
}
Output:
id of A: 100
id of B : 100
id of C: 100
id of D : 100
objects. This will enable the system to allocate the right amount of memory for
each object when the objects are not of the same size, thus resulting in the
return 0;
Dalcomp
} Technologies 117
Output:
Dalcomp
Technologies
Chinchwad
Dalcomp Technologies
Dalcomp Technologies Chinchwad
Add( ) ; // No arguments
void main()
{
rectangle rc1(3.0, 2.0); //invokes parameterized constructor definition
rectangle rc2(); //invokes default constructor definition
rc1.draw();
rc2.draw();
}
Home
Dalcomp Technologies 128
Chapter 6
Inheritance: Extending Classes
Introduction
Private, Public & Protected Inheritance
Advantages Of Inheritance
Types Of Inheritance
Single Inheritance
Multilevel Inheritance
Multiple Inheritance
Hierarchical Inheritance
Hybrid Inheritance
Virtual Base Class
With the help of inheritance we uses the code & data that is
previously defined in the base class.
Data hiding -- base class can decide to keep some data private
so that it cannot be altered by the derived class
1. Single Inheritance
2. Multilevel Inheritance
3. Multiple Inheritance
4. Hierarchical Inheritance
5. Hybrid Inheritance
class emp
{
public: int eno;
char name[20],des[20];
void get()
{
cout<<"Enter the employee number:";
cin>>eno;
cout<<"Enter the employee name:";
cin>>name;
cout<<"Enter the designation:";
cin>>des;
}
Dalcomp Technologies 135
};
class salary:public emp
{
float bp,hra,da,pf,np;
public: void get1()
{ cout<<"Enter the basic pay:";
cin>>bp;
cout<<"Enter the Humen Resource Allowance:";
cin>>hra;
cout<<"Enter the Dearness Allowance :";
cin>>da;
cout<<"Enter the Profitablity Fund:";
cin>>pf;
}
void calculate()
{
np=bp+hra+da-pf;
}
Dalcomp Technologies 136
void display()
{
cout<<eno<<"\t"<<name<<"\t"<<des<<"\t"<<bp<<"\t"<<hra<<"\t"<<da<<"\t"<<pf<<
<<np<<"\n";
}
};
void main()
{
int i,n;
char ch;
salary s[10];
clrscr();
cout<<"Enter the number of employee:";
cin>>n;
for(i=0;i<n;i++)
{
s[i].get();
s[i].get1();
s[i].calculate();
}
Dalcomp Technologies 137
cout<<"\ne_no \t e_name\t des \t bp \t hra \t da \t pf \t np \n";
for(i=0;i<n;i++)
s[i].display();
getch();
}
• /* end of program*/
d.display();
getch();
}
Protected
class D1: public B class D2: private B
Public
Private
Private
Protected
Protected
Public class X: public D1:protected D2
Public
Private
Protected
Public
Dalcomp Technologies 146
Derived Class Visibility
Base Class visibility
Public Private Protected
derivation derivation derivation
BASE CLASS
DERIVED CLASS 1
DERIVED CLASS 2
Derived Class
Base Class
Derived Derived
Class 3 Class 2
In the below example the derived class "res" uses the function "put_num()".
Result:
B C
x= 5
y = 10.75
m = 20
n = 30
Home
Dalcomp Technologies 167
Chapter No.7
Virtual Functions
Polymorphism In C++
Applying Polymorphism
Polymorphism
Compile-time Run-time
Polymorphism Polymorphism
Function Operator
Virtual Functions
Overloading Overloading
• Two types :
o Compile time polymorphism
• Uses static or early binding
• Example: Function and operator overloading
o Run time polymorphism
• Uses dynamic or late binding
• Example: Virtual functions
Let we have –
o class base { … };
derived d_obj;
p1 = &d_obj;
{ { base b1;
} Here,
}; };
void main() {
class d1: public base {
base *pb; d1 od1; d2 od2;
public:
int n;
void show() {
cin >> n;
cout << “derived -1\n”;
if (n % 2 ==0)
} { pb = &od1;
}; else pb = &od2;
below example we can see that the function is base class never
functions.
Home
Dalcomp Technologies 183
Chapter 8.
Operator Overloading
Introduction
Type Conversions
C++ has ability to provide the operators with a special meaning for a data
types.
We can overload (give additional meaning to) all the C++ operators except:
o Class member access operators ( . & .*)
o Scope resolution operators ( : : )
o Size operator (sizeof)
o Conditional operators (? : )
When operators are used with objects, then they have meaning appropriate
to those objects.
For example, ‘+’ should be used for addition, not subtraction. Otherwise this
formed using the keyword ‘operator’ followed by the symbol for the
Non- member operator functions are generally friend functions of the class.
Dalcomp Technologies 187
Operators that Can and Cannot be
Overloaded
Operators that can be overloaded
+ - * / % ^ & |
~ ! = < > += -= *=
/= %= ^= &= |= << >> >>=
<<= == != <= >= && || ++
-- ->* , -> [] () new delete
new[] delete[]
. .* :: ?:
cin>>a>>b;
obj1.setValue(a); Output:
obj2.setValue(b); Enter the value of Complex
Numbers a,b: 10 5
Input Values:
result = obj1+obj2; 10
cout<<"Input Values:\n"; 5
obj1.display(); Result:15
obj2.display();
{
complex t;
t.a=a-ob.a;
t.b=b-ob.b;
return(t);
}
void display()
{
cout<<a<<"+"<<b<<"i"<<"\n";
}
};
OUTPUT:
i=7 j=8
int b = a; then b = 2;
2. Explicit Type Conversion :- This conversion is explicitly done using type cast
operator.
cout<<“\nStock Value”<<“\n”;
cout<<“Value = ”<<total_value<<“\n\n”;
cout<<“Product Details – invent 2type”<<“\n”;
d1.putdata();
return 0;
}
Home
Dalcomp Technologies 203
Chapter 9
Introduction To C++ I/O System
Introduction To Streams
Iostream Library Header Files
Stream Input/Output Classes and Objects(I)
Stream Input/Output Classes and Objects (II)
Stream Output
Stream-Insertion Operator
Stream-Insertion/Extraction Operators
Stream Input
I/O Operations:
Input: A stream that flows from an input device ( i.e.:
keyboard, disk drive, network connection) to main memory
Output: A stream that flows from main memory to an
output device ( i.e.: screen, printer, disk drive, network
connection)
Low-level I/O
o Unformatted
o Individual byte unit of interest
o High speed, high volume, but inconvenient for people
High-level I/O
o Formatted
o Bytes grouped into meaningful units: integers, characters, etc.
o Good for all I/O except high-volume file processing
iostream library:
o <iostream.h>: Contains cin, cout, cerr, and clog objects
Home
Dalcomp Technologies 216
Chapter 10
Exception Handling
Introduction To Exceptions
Introduction To Throw
Catch(){}
#include <iostream>
using namespace std;
int main ()
{
try
{
throw 10;
}
catch (int e)
{
cout << “We have a problem!!” << endl;
}
return 0;
Output
} : We have a problem!!!
The catch(…) handler catches all exceptions, no matter what type. It can be
used as a default handler if declared last.
getch();
}
Output:
Enter the value for a: 20
Enter the value for b: 20
Enter the value for c: 40
catch(int x)
{
cout<<"Catch a integer and that integer is:"<<x;
}
Home
Dalcomp Technologies 227
Chapter 11.
Templates
Introduction To Templates
Types Of Templates
Points To Remember
Dalcomp Technologies 228
Introduction To Templates
Some compilers support templates poorly. So, the use of templates could
A compiler generates an additional code for each data type which results in
larger executables.
compilers.
The use of templates makes the code less portable as all features are
1. Function Template
2. Class Template
parameters is:
int main () {
int i=5, j=6, k;
long l=10, m=5, n;
k=GetMax(i,j);
n=GetMax(l,m); 6
cout << k << endl; 10
cout << n << endl;
return 0;
}
For example:
template <class T>
class mypair
{
T values [2];
public:
mypair (T first, T second)
{
values[0]=first; values[1]=second;
}
};
OUTPUT: 100
Home
Dalcomp Technologies 247
Chapter No.12
File Handling
Using Input/Output Files
General File I/O Steps
Streams
Predefined console streams
Why to use Files?
Classes for Stream I/O in C++
File Modes
File pointers
Dealing with Binary files
Binary File I/O Examples
media.
The data of a file is stored in either readable form or in binary code called as
A computer file
o is permanent;
Associate the file name variable with the disk file name
The get pointer specifies a location from which the current reading
operation is initiated
Other is called the output pointer or put pointer.
The put pointer specifies a location from where the current writing
operation is initiated
We can use these pointers to move through the files while reading or
writing.
The input pointer is used for reading the contents of a given file location and
the output pointer is used for writing to a given file location.
Functions for manipulation of file pointers
seekg() Moves get pointer (input) to a specified location.
seekp() Moves put pointer (output) to a specified location.
tellg() Gives the current position of the get pointer.
tellp() Gives the current position of the put pointer.
File Open Mode
#include <fstream>
int main(void)
{
ofstream outFile("file1.txt", ios::out);
outFile << "That's new!\n";
outFile.close();
Return 0;
}
If you want to set more than one open mode, just use the OR
operator- |. This way:
ios::ate | ios::binary
Dealing with Binary files
• Functions for binary file handling
get(): read a byte and point to the next byte to read
put(): write a byte and point to the next location for write
read(): block reading
write(): block writing
#include <fstream>
using namespace std;
int main(void)
{
ofstream outFile(“fout.txt");
outFile << "Hello World!";
outFile.close();
return 0;
}
File I/O Example: Reading
#include <iostream>
#include <fstream>
int main(void)
{
ifstream openFile(“data.txt"); //open a text file data.txt
char ch;
while(!OpenFile.eof())
{
OpenFile.get(ch);
cout << ch;
}
OpenFile.close();
return 0;
}
File I/O Example: Reading
#include <iostream>
#include <fstream>
#include <string>
int main(void)
{
ifstream openFile(“data.txt"); //open a text file data.txt
string line;
if(openFile.is_open()){ //
while(!openFile.eof()){
getline(openFile,line);//read a line from data.txt and put it in a string
cout << line;
}
else{
cout<<“File does not exist!”<<endl;
exit(1);}
}
openFile.close();
return 0;
}
To access file handling routines:
#include <fstream.h>
1: To declare variables that can be used to access file:
ifstream in_stream;
ofstream out_stream;
2: To connect your program's variable (its internal name) to an
external file (i.e., on the Unix file system):
in_stream.open("infile.dat");
out_stream.open("outfile.dat");
3: To see if the file opened successfully:
if (in_stream.fail())
{ cout << "Input file open failed\n";
exit(1); // requires <stdlib.h>}
To get data from a file (one option), must declare a variable to
hold the data and then read it using the extraction operator:
int num;
in_stream >> num;
[Compare: cin >> num;]
4: To put data into a file, use insertion operator:
out_stream << num;
[Compare: cout << num;]
NOTE: Streams are sequential – data is read and written in order
– generally can't back up.
5: When done with the file:
in_stream.close();
out_stream.close();
Reading /Writing from/to Binary Files
To write n bytes:
write (const unsigned char* buffer, int n);
To read n bytes (to a pre-allocated buffer):
read (unsighed char* buffer, int num)
#include <fstream.h>
main()
{
int array[] = {10,23,3,7,9,11,253};
ofstream OutBinaryFile("my_b_file.txt“, ios::out | ios::binary);
OutBinaryFile.write((char*) array, sizeof(array));
OutBinaryFile.close();
}
C++ has some low-level facilities for character I/O.
char next1, next2, next3;
cin.get(next1);
Gets the next character from the keyboard. Does not skip over
blanks or newline (\n). Can check for newline (next == '\n')
Example:
o cin.get(next1);
o cin.get(next2);
o cin.get(next3);
Predefined character functions must #include <ctype.h> and can
be used to
• convert between upper and lower case
• test whether in upper or lower case
• test whether alphabetic character or digit
• test for space
Reading /Writing from/to Textual Files
#include <fstream.h>
To write: main()
{
put() – writing single character // Writing to file
<< operator – writing an object ofstream OutFile("my_file.txt");
OutFile<<"Hello "<<5<<endl;
To read: OutFile.close();
get() – reading a single character
int number;
of a buffer char dummy[15];
getline() – reading a single line
>> operator – reading a object // Reading from file
ifstream InFile("my_file.txt");
InFile>>dummy>>number;
InFile.seekg(0);
InFile.getline(dummy,sizeof(dummy));
InFile.close();
}
Binary file operations
In connection with a binary file, the file mode must
contain the ios::binary mode along with other mode(s)
#include <fstream>
using namespace std;
int main(){
ifstream in(“binfile.dat”);
ofstream out(“out.dat”);
if(!in || !out) { // return}
unsigned int buf[1024];
while(!in){
in.read(buf, sizeof(unsigned
int)*1024);
out.write(buf, sizeof(unsigned
int)*1024);
}
End Of Chapter 12.
Any Question?
Home
Dalcomp Technologies 276
Thank You
Dalcomp Technologies
Home 280