CS-235 0bject Oriented Programming With C++ Complete Lecture Notes
CS-235 0bject Oriented Programming With C++ Complete Lecture Notes
**
CS213 2
Programming in C++ / Session 1 / 2 of 45
The Object-Oriented approach
Accounts
Personnel
Sales
**
CS213 3
Programming in C++ / Session 1 / 3 of 45
Drawbacks of Traditional Programming
Fortran : not structured (uses goto)
Pascal/ C : Structured (less use of goto),
subroutines/function to add modularity or more
structure, but modularity only at functional level
C++ : modularity at both functional and data level
In C programs are organized around the code what
is happening
In C++ programs are organized around the data
who is being affected.
**
CS213 4
Programming in C++ / Session 1 / 4 of 45
Introduction to OOP
OOP allows for analysis and design of an application
in terms of entities or objects.
**
CS213 5
Programming in C++ / Session 1 / 5 of 45
Data and Functions of an Object
Accounts
Data: Functions:
**
CS213 6
Programming in C++ / Session 1 / 6 of 45
Objects
Incorporate a combination of a set of data values as data
members, and the set of operations as member function.
**
CS213 7
Programming in C++ / Session 1 / 7 of 45
Different Objects
Actions:
Walk Actions:
Talk Start
Sleep Stop
Accelerate
**
CS213 8
Programming in C++ / Session 1 / 8 of 45
Classes
Class is a logical abstraction for representing various objects
having similar attributes/properties.
**
CS213 9
Programming in C++ / Session 1 / 9 of 45
Objects and Classes
Polygon class
Polygon objects
Properties:
Vertices
Border color
Abstract Fill color
into Methods:
Draw
Erase
Move
**
CS213 10
Programming in C++ / Session 1 / 10 of 45
Property/Attribute
• Each object ie instance of the class has its own value
for each of its properties but it shares the property
names or operations with other instances of the class
(object).
**
CS213 11
Programming in C++ / Session 1 / 11 of 45
Method
What is the salary The black box actually contains
of Jack code
Sales
The communication between
objects is done using
messages.
**
CS213 12
Programming in C++ / Session 1 / 12 of 45
Abstraction
Process of examining certain aspects of a problem.
An abstract specification tells us what an object does
independent of how it works.
In C++ an abstraction indicates what data can an object
hold and what functions can it perform on the data. How
these functions are performed is abstracted away
**
CS213 13
Programming in C++ / Session 1 / 13 of 45
Inheritance
The property that allows the reuse of an existing class to
build a new class. The derived class inherits all the
capabilities of the base class and can either refine some
of its features or add totally new features of its own
Superclass - The class from which another class
inherits its behaviour.
Subclass - The class that inherits the properties and
methods of another class.
Inheritance works the same way as in real life. Children inherit
features from their parents, refine some of them and add a few of
their own
**
CS213 14
Programming in C++ / Session 1 / 14 of 45
Class Animals and its subclasses
Animals
**
CS213 15
Programming in C++ / Session 1 / 15 of 45
Encapsulation
**
CS213 16
Programming in C++ / Session 1 / 16 of 45
Polymorphism
Polymorphism means the ability to assume several
forms. In object oriented programming context this
refers to the ability of an entity to refer to objects of
various classes at run time
Three types in C++
Function overloading Compile time polymorphism
Operator overloading
**
CS213 17
Programming in C++ / Session 1 / 17 of 45
C++ Program Structure
C++ is a structured programming language
# include <iostream.h>
void main()
{
cout << “ Hello there !!! “ ;
}
Output:
**
CS213 19
Programming in C++ / Session 1 / 19 of 45
Standard I/O streams
Input Stream
The following object, in combination with its corresponding
insertion operator performs input in C++. >> operator stops reading after
seeing the first white space
Output Stream
The following object, in combination with its corresponding
extraction operator performs output in C++.
**
CS213 21
Programming in C++ / Session 1 / 21 of 45
Cascading I / O Operators
The input and output streams can be used in combination.
**
CS213 22
Programming in C++ / Session 1 / 22 of 45
Certain Essentials
The essential components of a program construct are:
exampleclass object1,object2;
**
CS213 31
Programming in C++ / Session 1 / 31 of 45
Two objects with different values
object_data
object_data object1
200
Specifications for
Objects of the class
exampleclass objects
exampleclass
object_data
350
object2
exampleclass
class specifier
**
CS213 34
Programming in C++ / Session 1 / 34 of 45
CS213 35
Programming in C++ / Session 1 / 35 of 45
Introduction
Identifier
**
CS213 36
Programming in C++ / Session 1 / 36 of 45
Special characters
[] () . -> ++ -- &
* + - ~ ! \ /
% << >> < > <= >=
== != ^ && | || ?:
= *= /= %= += -= <<=
>>= &= ^= |= , # ##
CS213 37
Programming in C++ / Session 1 / 37 of 45
Escape sequences
Back space
New line
Tab
Carriage return
Form feed
Single quote
CS213 38
Programming in C++ / Session 1 / 38 of 45
Escape sequences (1)
Back slash
Bell
Octal number
given by ooo
Hexadecimal number
given by hh
CS213 39
Programming in C++ / Session 1 / 39 of 45
Identifiers
CS213 41
Programming in C++ / Session 1 / 41 of 45
Keywords
Keywords, inherited from the C language
New in C++
CS213 42
Programming in C++ / Session 1 / 42 of 45
Data Types and Variables
CS213 43
Programming in C++ / Session 1 / 43 of 45
Another predefined data type of C++ :: bool
bool data type : can store true and false
true or false are the keywords defined in C++
int num ;
int num1 = 3; optional
char alpha = ‘G’ ; C requires that all variables be
declared before the first executable
float float_no ; statement. Whereas C++ allows
declaration of variables anywhere in
float floa = 33.33; the program. So you can declare
double d_no ; variables at the point where they
are used
double doub = 1234.121212121
; CS213 46
Programming in C++ / Session 1 / 46 of 45
Access modifiers
The value of the variable defined as constant will not be allowed to change through
out the program. So in purpose const is similar to #define
const is a better idea as compared to #define because its scope of operation can be
controlled by placing it appropriately either inside a function or outside all functions
CS213 51
Programming in C++ / Session 1 / 51 of 45
const pointers
const char *q = “Hello”; //string is constant but pointer q is not constant
*q = ‘M’; // error
q = “bye” //ok
The above is similarly also applicable to integer pointer, floating point pointers etc
CS213 58
Programming in C++ / Session 1 / 58 of 45
Returning const value
A function can return a pointer to a constant string as shown below
#include <iostream.h>
void main() {
const char *fun();
const char *p;
p = fun(); // since fun() is returning a const value so in main() we are not allowed to assign the
//return value to a pointer to a non const value . Ie p must be a pointer to const string.
*p = ‘a’; // error as p is a pointer to constant string whose contents can not be changed
cout << p;
}
CS213 59
Programming in C++ / Session 1 / 59 of 45
Precedence and Order of Evaluation
CS213 70
Programming in C++ / Session 1 / 70 of 45
Conversion table
CS213 72
Programming in C++ / Session 1 / 72 of 45
Type casting
Often leads to
Use explicit type conversions
in mixed mode expressions
N = (y-1) * (long) j ; // C style of typecasting ; also supported by C++
float a ;
(int) a ; N = (y-1) * long(j); // new C++ style of typecasting
CS213 74
Programming in C++ / Session 1 / 74 of 45
The :: operator
:: is a scope resolution operator
#include < iostream.h>
Int a=10; // global a
Void main() {
Int a = 15; // local a
cout << “\n local a =“ << a << “global a = “ << ::a;
}
CS213 79
Programming in C++ / Session 1 / 79 of 45
The break Statement
CS213 109
Programming in C++ / Session 1 / 109 of 45
The continue Statement
CS213 112
Programming in C++ / Session 1 / 112 of 45
The exit() Construct
exit(int return_code)
CS213 114
Programming in C++ / Session 1 / 114 of 45
Return from functions
CS213 123
Programming in C++ / Session 1 / 123 of 45
Return from functions
CS213 125
Programming in C++ / Session 1 / 125 of 45
Scope of Variables
CS213 126
Programming in C++ / Session 1 / 126 of 45
Scope of Variables
int gi_area; // Declaring a global variable
void main(void)
{ void using_globalvar(void);
void g_func(void) ;
int li_len, li_wid; //Declaring local variables
:
:
using_globalvar() ; //Function call
}
void using_globalvar(void)
{
cout << "\nArea = " << gi_area; // Global variable
getch() ;
return ;
}
CS213 128
Programming in C++ / Session 1 / 128 of 45
Actual and Formal parameters
The parameter specified during a function call
CS213 131
Programming in C++ / Session 1 / 131 of 45
The sizeof() operator
CS213 135
Programming in C++ / Session 1 / 135 of 45
Storage classes
auto
static
extern
register
CS213 139
Programming in C++ / Session 1 / 139 of 45
Auto storage class
Automatic variables do not retain the
value over a number of function calls
CS213 140
Programming in C++ / Session 1 / 140 of 45
Static storage class
Static variables retain their values
over a number of function calls
CS213 141
Programming in C++ / Session 1 / 141 of 45
Static storage class
void print_auto(void)
{
static int i = 0 ;
auto j = 0;
cout << "\nValue of i before incrementing = " << i ;
cout << "\nValue of j before incrementing = " << j ;
i += 10 ;
j += 10 ;
cout << "\nValue of i after incrementing = " << i ;
cout << "\nValue of i after incrementing = " << j ;
}
CS213 142
Programming in C++ / Session 1 / 142 of 45
Static storage class
void main(void)
{
clrscr() ;
print_auto() ;
cout<<”\n”;
print_auto() ;
cout<<”\n”;
print_auto() ;
}
CS213 143
Programming in C++ / Session 1 / 143 of 45
Extern storage class
CS213 144
Programming in C++ / Session 1 / 144 of 45
Extern storage class
CS213 145
Programming in C++ / Session 1 / 145 of 45
Register storage class
Register memory is a part of
microprocessor itself
CS213 147
Programming in C++ / Session 1 / 147 of 45
Pointers
A pointer is a variable that we can use to store a memory address.
CS213 148
Programming in C++ / Session 1 / 148 of 45
Pointers
char v, *pv
v = 'A' ;
pv = &v ;
CS213 149
Programming in C++ / Session 1 / 149 of 45
Pointer operation
int *p1, *p2;
p1 + 4, p2 – 2, p1++, --p2 are valid operation
p2 - p1 is valid and gives the no. of elements between p1 &
p2 if p1 & p2 both are pointers to the same array
Pointers can be compared p1 > p2, p1 ==p2, p1 != p2
are all valid operation
p1 + p2, p1/p2 , p1 * p2, p1/3. p2 * 5 invalid operations
CS213 151
Programming in C++ / Session 1 / 151 of 45
void pointers
In C++ special care has to be taken to handle the assignment of
void pointers to other pointer types
void *p;
Char *s;
p = s; // valid
s = p; // invalid assignment should be s = (char *) p ;
While you can assign a pointer of any type to a void pointer, the
reverse is not true unless you specifically typecast it
CS213 152
Programming in C++ / Session 1 / 152 of 45
Call by value
When data is passed between functions using variable names
void main(void)
{
int data ;
:
:
call_function(data) ;
}
void call_function(int data)
{
cout << data ;
}
CS213 153
Programming in C++ / Session 1 / 153 of 45
Call by reference
When data is passed between functions using address of variables
void main(void)
1000
{ 1001 (data) 12 50
1002
int data ; 1003
1004
data =12; 1005 (p_data) 1001
1006
:
1007
: 1008
1009
call_function(&data) ;
}
1001
void call_function(int *p_data)
{
*p_data = 50
cout << *p_data ;
}
CS213 154
Programming in C++ / Session 1 / 154 of 45
Value modification
void funct1(int u, int v)
{
u = 0; v = 0;
}
void funct2(int *pu, int *pv)
{
*pu = 0 ; *pv = 0 ;
}
CS213 156
Programming in C++ / Session 1 / 156 of 45
Character Arrays
# include <iostream.h>
void main(void)
{
char name[10];
cout << “\nHello " << name << ". Welcome to Arrays!” ;
}
CS213 163
Programming in C++ / Session 1 / 163 of 45
Pointers and Arrays
An array of pointers can be created
(Int (*pt)[7] :: pointer to an
int *pt[7] ; array of 7 integers)
CS213 170
Programming in C++ / Session 1 / 170 of 45
Pointers and Arrays
Initializing array of character pointers
void main(void)
{
char *song[]= { “ Humpty dumpty sat on a wall\n”,
“ Humpty dumpty had a great fall\n”,
“ Not all the kings horses and men\n”
};
cout<<song[2];
}
Not all the kings horses and men
CS213 171
Programming in C++ / Session 1 / 171 of 45
Basic Introduction to Classes & Objects
// Example showing use of class and objects
#include <iostream>
using namespace std; // explained in next slide
#define SIZE 100
// This creates the class stack.
class stack {
int stck[SIZE]; // default scope is private
int tos;
int main()
public: // scope : discussed later
{
void init(); // Function declaration
stack stack1, stack2; // create two stack objects
void push(int i);
stack1.init(); // we access the class members
int pop();
// with the help of . operator
}; // we can declare an object here also but then it
stack2.init();
// will be a global object
stack1.push(1);
void stack::init() // function defination
stack2.push(2);
{
stack1.push(3);
tos = 0;
stack2.push(4);
}
cout << stack1.pop() << " ";
void stack::push(int i)
cout << stack1.pop() << " ";
{
cout << stack2.pop() << " ";
if(tos==SIZE) {
cout << stack2.pop() << "\n";
cout << "Stack is full.\n";
return 0;
return;
}
}
stck[tos] = i;
tos++;
}
int stack::pop()
{
if(tos==0) {
cout << "Stack underflow.\n";
return 0;
}
tos--;
return stck[tos];
}
Prepared by Dr. Naveen Choudhary 1
Prepared by Dr. Naveen Choudhary 2
Prepared by Dr. Naveen Choudhary 3
Defined in iostream
Prepared by Dr. Naveen Choudhary 4
Prepared by Dr. Naveen Choudhary 5
Prepared by Dr. Naveen Choudhary 6
Prepared by Dr. Naveen Choudhary 7
Prepared by Dr. Naveen Choudhary 8
Prepared by Dr. Naveen Choudhary 9
Constructors & Destructors
How to initialize data members (specially private members) of an object use
constructors
A constructor is a special function that is a member of a class and has the same name
as that of the class
Constructor do not return values & so constructor function has no return type
How constructor is called :: called when the object is declared. An object’s
constructor is called once for global or static local objects. For non static local
objects, the constructor is called each time the object declaration is encountered.
DESTRUCTORS
Syntax :: ~Class_name
Purpose : In many circumstances an object will need to perform some actions when it
is destroyed.
An object may need to de-allocate memory that it had previously allocated or it may
need to close a file that it had opened. So in C++, it is destructor’s function that
handles deactivation events.
when destructor is called :: when an object is destroyed, it’s destructor is
automatically called.
when an object is destroyed :: local objects are created when their block is
entered & destroyed when the block is left
Global objects are destroyed when program terminates
like constructor, destructors also do not have return values
struct mystr {
int a; // public by default
int b;
void showa();
void showb(char *s);
};
void mystr :: showa() {
.
.
}
ob.b2 = x1; }
int i; // global i
void f()
{
int i; // local i
::i = 10; // now refers to global i
.
.
.
}
Class Distance {
.
.
Public :
Distance(…, …) { ……. }
Void getlist() { …. }
{...... }
};
int main(){
ft.showdist(); // allowed
}
#include <iostream>
using namespace std; int i=4; int n[10];
int main() { int &x = n[10]; // x is alias for n[10]
int a;
int &ref = a;
int &j; //error char &a = '\n'; // initialised reference
/* independent reference must be initialized at the time of declaration */ //to a literal
a = 10; Int &j=4;//ok
cout << a << " " << ref << "\n"; int x;
/* a & ref both refer to the same value a=10, ref=10 */
ref = 100; J=i; int *p = &x;
cout << a << " " << ref << "\n"; // a=100, ref=100 int &m = *p; // so new m refers to x
int b = 19;
ref = b; // this puts b's value into a //(which is pointed to by
cout << a << " " << ref << "\n"; // a=19, ref = 19 // pointer P)
ref--; // this decrements a it does not affect what ref refers to
cout << a << " " << ref << "\n"; // a=18,ref=18 int &n = 50;
return 0;
}
// creates a int object with value 50
//and name n
#include <iostream>
using namespace std;
class cl {
int id; Output:- constructing 1
public:
int i; -10
cl(int i);
~cl(); destruction 1
void neg(cl &o) { o.i = -o.i; } note:- destructor is called only once
// no temporary object is created
}; ie when main() terminates
cl::cl(int num) {
cout << "Constructing " << num << "\n";
id = num;
Passing object by reference is faster
} than passing object by value. as there
cl::~cl() { is no need of making any copy &
cout << "Destructing " << id << "\n";
} putting on to the stack
int main() {
cl o(1);
o.i = 10;
o.neg(o);
cout << o.i << "\n";
return 0;
} Prepared by Dr. Naveen Choudhary 41
Reference
Function returning reference can be used on the left side (as well as on right side) of an
assignment statement. In other words when a function returns a reference, the function
call can exist in any context where a reference can exist
//the program replaces hello there with helloxthere Reference is an implicit constant
#include <iostream> pointer ie once a reference variable
using namespace std;
has been defined to refer to a
char &replace(int i); // return a reference
char s[80] = "Hello There"; particular variable, it can not refer to
int main() any other variable. that is, once the
{ variable and the reference are linked
replace(5) = 'X'; // assign X to space after Hello they are tied together inseparably.
cout << s;
return 0;
We can create reference to a
}
char &replace(int i) pointer
{ char *p = “Hello”;
return s[i]; char * &q = p;
}
A variable can have multiple
Note :: One thing to be careful about when returning
reference. changing the value of one
reference is that the object being referenced to
should not go out of scope after the function of them effects a change in all
terminates. That is do not try to return local variable others.
by reference
Q 2. Is reference a pointer?
Hint:- A reference is a const pointer . hence once initialized a reference cannot be made to refer
to another variable. Unlike a pointer a reference gets automatically de-referenced.
Also, arithmetic operation cannot be performed on a reference.This is shown in the following example:
main () {
int i;
int &r = i;
r++; // will not increment r but will increment the value of i
int *p = &i;
p++;
}
Here r++ would not increment the value of r. But it will increment value of i. This means that when an arithmetic
operation is performed on a reference, it gets performed on a referent. But when p++ is done, the value of p is
incremented.
Q 8 . Why should we not return a reference or an address of a local variable.
Hint:- When we return a reference of a local variable, the variable would die once control returns to the calling
function. Hence, calling function would be referencing to a variable that no longer exists.
Q 9. Can we create a reference to an array?
Hint:- Yes, a reference to an array is allowed. For example: Note: int (*pt)[7] :: pointer to an array of
int a[] = {3,7,6,9,5}; 7 integers
int(&p)[5] = a; // reference to an array int *pt[7] ; Array of 7 pointers
Q 10 Why is it so that when we print the address of a reference the address of a referent gets printed?
Once a reference is tied with a variable it cannot be tied with another variable
ANS: True. A reference being a const pointer, once initialized its value cannot be changed.
} 1009
100 (x)
Pointer arithmetic
We can add or subtract integer to or from pointers (p1 = p1 + 3)
We can subtract same type of pointer from another same type of pointer (to find the
no. of elements separating the two pointers in the array)
Pointers can be compared (<, <=, >, >=, ==, !=)
Pointes can not be multiplied or divided (p1/3, p*3, p1/p2, p1*p2 all these are
illegal operations on the pointer )
Can not add two pointers (p1 + p2 illegal)
We can not add or subtract type float or double to or from pointers (p + 2.14, p -
2.14 illegal)
Prepared by Dr. Naveen Choudhary 48
Dynamic memory allocation in C
Arrays & Pointers
Name of the array is actually the address of the first
element of the array
int num[] = { 24, 34, 12, 44, 56, 77 }; Address Array elements
//num == &num[0] == 1000 (&num[0]) 1000 24 (num[0])
num[i] ==*(num + i) == *( i + num) == i[num]
(&num[1]) 1004 34 (num[1])
*(Num+0)
Num
*(Num +1)
P
int *
P 0 0 /1002 0/1004 0/1006
(1000) /1000 int *
1/1008 1/1010 1/1012 1/1014 Int *
functions are overloaded beside they have Constructor functions can also be overloaded
different type of arguments.
Dynamically allocated Array (of objects) can not be
initialized so a parameter less constructor is a
int myfunc (int i) must in such cases
int myfunc (int i, int j) but if you need initialized version of objects also
then you should have (with parameters)
overloaded as they differ in number of constructor also
parameters
Note : example on next slide
int myfunc (int i)
float myfunc (int i)
class name(const class name & o){ When a temparary object is genareted (most
// body of the constructor commonly as a return value)???
}
y = func(); // y receives a temporary (returned)
It is important to understand that C++ defined //object(copy constructor is called
two distinct type of situation in which the value //here). However at the time of
of one object is given to another. //assignment of the returned
Assignment & initialization //value(object) to y, the overloaded
//assignment operator if any will be
//called
Copy Constructor initialization Assignment
class c1{
myclass x = y; // y explicitly initializating x -------------
}
func(y); // y passed as a parameter int main (){
c1 ob1, ob2;
y = func(); // temporary object generated as return
Prepared by Dr. Naveen Choudhary--------------- 62
//value ob1=-ob2; //Assignment
Copy constructor
// Copy Constructor
/* This program creates a "safe" array class. Since space
array::array(const array &a) {
for the array is allocated using new, a copy constructor
int i;
is provided to allocate memory when one array object is
try {
used to initialize another. */
p = new int[a.size];
#include <iostream>
} catch (bad_alloc xa) {
#include <new>
cout << "Allocation Failure\n";
#include <cstdlib>
exit(EXIT_FAILURE);
using namespace std;
}
for(i=0; i<a.size; i++) p[i] = a.p[i];
class array {
}
int *p;
int main()
int size;
{
public:
array num(10);
array(int sz) {
int i;
try {
for(i=0; i<10; i++) num.put(i, i);
p = new int[sz];
for(i=9; i>=0; i--) cout << num.get(i);
} catch (bad_alloc xa) {
cout << "\n";
cout << "Allocation Failure\n";
// create another array and initialize with num
exit(EXIT_FAILURE);
array x(num); // invokes copy constructor
}
for(i=0; i<10; i++) cout << x.get(i);
size = sz;
return 0;
}
}
~array() { delete [] p; }
// copy constructor
array(const array &a);
void put(int i, int j) {
if(i>=0 && i<size) p[i] = j;
}
int get(int i) {
return p[i];
}
};
3. funct1{
array Num;
---------
----------
return Num;
}
main() {
array a;
-----
----
a= funct1();
}
array a (10)
array b(10);
b=a; // does not call copy constructor, rather it is an assignment so bitwise copy will take place & in several
condition to avoid bitwise copy we need to overload the = operator
int myfunc(int a) {
return a;
}
int main() {
#include <iostream> // Overload assignment for loc.
loc ob1(10, 20), ob2;
using namespace std; loc loc::operator=(loc op2) {
ob1.show();
class loc { longitude = op2.longitude;
int longitude, latitude; latitude = op2.latitude; ++ob1;
ob1.show(); // displays 11
public: return *this; // i.e., return object
// 21
loc() {} //that generated call
ob2 = ++ob1;
loc(int lg, int lt) { }
longitude = lg; // Now a friend; use a reference ob2.show(); // displays 12
// 22
latitude = lt; //parameter.
--ob2;
} loc operator++(loc &op) {
ob2.show(); // displays 11
void show() { op.longitude++;
// 21
cout << longitude << " "; op.latitude++;
return 0;
cout << latitude << "\n"; return op;
}
} }
loc operator=(loc op2); // Make op-- a friend; use reference. //for post increment in friend
friend loc operator++(loc &op); loc operator--(loc &op) { //function a extra dummy
friend loc operator--(loc &op); op.longitude--; //argument will be reqired
// friend, postfix version of ++ op.latitude--;
//friend loc operator++(loc &op, int x); return op;
}; }
Prepared by Dr. Naveen Choudhary
Where friend is a must ?
object + integer } ob + 100;
integer + object } 100 + ob;
// overloaded operator member function can not work, so in such cases friend operator
// overloaded function is necessary.
// + is overloaded for int + loc.
#include <iostream>
loc operator+(int op1, loc op2) {
using namespace std;
loc temp;
class loc {
temp.longitude = op1 + op2.longitude;
int longitude, latitude;
temp.latitude = op1 + op2.latitude;
public:
return temp;
loc() {}
}
loc(int lg, int lt) {
int main() {
longitude = lg; latitude = lt;
} loc ob1(10, 20), ob2( 5, 30), ob3(7, 14);
ob1.show();
void show() {
ob2.show();
cout << longitude << " ";
ob3.show();
cout << latitude << "\n";
ob1 = ob2 + 10; // both of these
}
ob3 = 10 + ob2; // are valid
friend loc operator+(loc op1, int op2);
ob1.show();
friend loc operator+(int op1, loc op2);
ob3.show();
};
return 0;
// + is overloaded for loc + int.
}
loc operator+(loc op1, int op2) {
loc temp;
temp.longitude = op1.longitude + op2;
temp.latitude = op1.latitude + op2;
return temp; Prepared by Dr. Naveen Choudhary
}
Overloading new & delete
allocate an object
void * operator new (size_t, size)
size no. of bytes to be allocate {\\ size_t (in #include<new> )is a defined type capable of
containing the largest single piece of memory that can be allocated }
Delete an object
void operator delete (void *p) //pointer to the memory to be freed
{
/*1. Free memory pointed to by p
2. Destruction called automatically */
}
Note:- The new and delete operators may be overloaded globally so that all users of these
operators call your custom versions. they may also be overloaded relative to one or more
class. The example below overloads new & delete relative to a class
Prepared by Dr. Naveen Choudhary
Overloading new & delete
#include <iostream>
#include <cstdlib> // delete overloaded relative to loc.
#include <new> void loc::operator delete(void *p) {
using namespace std; cout << "In overloaded delete.\n";
class loc { free(p);
int longitude, latitude; }
public: int main()
loc() {} {
loc(int lg, int lt) { loc *p1, *p2;
longitude = lg; try {
latitude = lt; p1 = new loc (10, 20);// float *f = new float;
} // uses default new
void show() { } catch (bad_alloc xa) {
cout << longitude << " "; cout << "Allocation error for p1.\n";
cout << latitude << "\n"; return 1;
} }
void * operator new(size_t size); try {
void operator delete(void *p); p2 = new loc (-10, -20);
}; } catch (bad_alloc xa) {
// new overloaded relative to loc. cout << "Allocation error for p2.\n";
void * loc::operator new(size_t size) return 1;;
{ }
void * p; p1->show();
cout << "In overloaded new.\n"; p2->show();
p = malloc(size); delete p1;
if(!p) { delete p2;
bad_alloc ba; return 0;
throw ba; }
}
return p; Prepared by Dr. Naveen Choudhary
}
Overloading new & delete
Note:- When new or delete are encountered, the compiler first checks to see whether they are
defined relative to the class they are operating on. if so, those specific versions are used. if not,
C++ uses the globally defined new & delete. if these have been overloaded, the overloaded
version are used.
// Global new
try {
#include <iostream> void *operator new(size_t size) p2 = new loc (-10, -20);
#include <cstdlib> { } catch (bad_alloc xa) {
#include <new> void *p; cout << "Allocation error for
using namespace std; p = malloc(size); p2.\n";
class loc { if(!p) { return 1;
int longitude, latitude; bad_alloc ba; }
public: throw ba; try {
loc() {} } f = new float; // uses overloaded
loc(int lg, int lt) { return p; //new, too
longitude = lg; } } catch (bad_alloc xa) {
latitude = lt; // Global delete
cout << "Allocation error for f.\n";
} void operator delete(void *p) { return 1;;
void show() { free(p); }
cout << longitude << " "; } *f = 10.10F;
cout << latitude << "\n"; int main() cout << *f << "\n";
} { p1->show();
}; loc *p1, *p2; p2->show();
float *f; delete p1;
try { delete p2;
p1 = new loc (10, 20); delete f;
} catch (bad_alloc xa) { return 0;
cout << "Allocation error for
}
p1.\n";
return 1;
} Prepared by Dr. Naveen Choudhary
overloading new & delete for arrays
if you want to be able to allocate arrays of objects using your own
allocation system, you will need to overload new & delete a second time.
//allocate an array of objects
void * operator new[] (size_t, size)
{
/* 1. perform allocation throw bad-allocation on failure
2. constructor for each element called automatically
3. return pointer-to-memory; */
}
// delete an array of objects
void operator delete[] (void*p)
{
/* 1. Free memory pointed to by p
2. Destruction for each element called automatically */
}
Note:- When allocating an array, the constructor function for each object in the
array is automatically called. when freeing an array, each objects destructor is
automatically called. you do not have to provide explicit code to accomplish these
actions. Prepared by Dr. Naveen Choudhary
overloading new & delete for arrays
// delete overloaded relative to loc.
#include <iostream> int main()
#include <cstdlib> void loc::operator delete(void *p) {
{
#include <new> loc *p1, *p2;
cout << "In overloaded delete.\n";
using namespace std; int i;
free(p);
class loc { try {
}
int longitude, latitude; p1 = new loc (10, 20);
// new overloaded for loc arrays.
public: // allocate an object
void *loc::operator new[](size_t size)
loc() {longitude = latitude = 0;} } catch (bad_alloc xa) {
{
loc(int lg, int lt) { cout << "Allocation
void *p;
longitude = lg; error for p1.\n";
cout << "Using overload new[].\n";
latitude = lt; } return 1;;
p = malloc(size);
void show() { }
cout << longitude << " "; if(!p) { try {
bad_alloc ba;
cout << latitude << "\n"; } p2 = new loc [10];
throw ba;
void *operator new(size_t size); // allocate an array
}
void operator delete(void *p); } catch (bad_alloc xa) {
return p;
void *operator new[](size_t size); cout << "Allocation
}
void operator delete[](void *p); error for p2.\n";
// delete overloaded for loc arrays.
}; return 1;;
// new overloaded relative to loc. void loc::operator delete[](void *p) }
{
void *loc::operator new(size_t size) p1->show();
cout << "Freeing array using overloaded
{
delete[]\n";
void *p; for(i=0; i<10; i++)
cout << "In overloaded new.\n"; free(p); p2[i].show();
}
p = malloc(size); delete p1; // free an
if(!p) { //object
bad_alloc ba; delete [] p2; // free an
throw ba; //array
} return 0;
Prepared by Dr. Naveen Choudhary
return p; }
Type conversion
int m;
float x = 3.14159;
m = x; // automatic type conversion take place
cout<<m; // 3 will be displayed
How the conversion from built-in type to class type will take place {
constructor with single argument}
How the conversion from class type to built-in type take place {
overloading casting function/ converts an operator}
how the conversion from one class type to another class type.
Will take place -> {constructor in destination class / conversion operation
in source class}
The casting operator ( or conversion) function should satisfy the following conditions.
it must be a class member
it must not specify a return type ( as by default it is the basic type to which the class is being
converted) Prepared by Dr. Naveen
it must not have any arguments ( the invoking object is used as an argument) Choudhary
one class to another class
obj x = obj y
Prepared
by
Naveen Choudhary
Prepared by Dr. Naveen Choudhary 1
Inheritance
Whatever is the access : private members of the base
Base class Derived class class can not be accessed in the derived class
int main()
#include <iostream>
{
using namespace std;
derived ob(3, 4, 5);
class base1 {
ob.show(); // displays 4 3 5
protected:
return 0;
int i;
}
public:
base1(int x) { i=x; cout << "Constructing base1\n"; }
Passing an argument along to a base class does not
~base1() { cout << "Destructing base1\n"; }
preclude its use by the derived class as well
};
class derived : public base
class base2 {
{ int i;
protected:
public:
int k;
// derived use both x & y and then passes them to base
public:
derived (int x, int y) :base (x,y)
base2(int x) { k=x; cout << "Constructing base2\n"; }
{
~base2() { cout << "Destructing base1\n"; }
j = x * y; cout<<"Constructing derived ";
};
}
class derived: public base1, public base2 {
Note:- One final point to keep in mind when passing
int j;
arguments to base-class constructors, the argument
public:
can consist of any expression valid at the time. this
derived(int x, int y, int z): base1(y), base2(z)
includes function calls and variable. this is in keeping
{ j=x; cout << "Constructing derived\n"; }
with the fact that C++ allows dynamic initialization.
~derived() { cout << "Destructing derived\n"; }
void show() { cout << i << " " << j << " "Prepared
<< k << "\n";
by Dr.} Naveen Choudhary 6
};
Virtual Base classes
/* derived3 inherits both derived1 and derived2.
A element of ambiguity can be introdcued into c++
This means that there are two copies of base
program when multiple base class are inherited
in derived3! */
Polymorphism
Virtual function -> Basic concept -> One interface, multiple methods
1. A virtual function is a member function that is declared within a base class and redefined by
a derived class. To create a virtual function, precede the function's declaration in the base
class with the keyword virtual. when a class containing a virtual function is inherited, the
derived class redefines the virtual function to fit its own needs.
2. When a base pointer points to a derived object that contain a virtual function, c++
determines which version of that function to call based upon the type of object pointed to
by the pointer. And this determination is made at runtime. thus when different objects are
pointed to by the pointer; the different versions of the virtual functions are executed.
2. base_class b1;
base_class *bp1;
derived_class d1;
bp1 = &d1;
bp1->func_name(int) ; // 1. derived version of virtual function is called
// 2. decision is made at run-time
/* Here, a base class reference is used to access // Use a base class reference parameter.
a virtual function. */ void f(base &r) {
#include <iostream> r.vfunc();
using namespace std; }
class base { int main()
public: {
virtual void vfunc() { base b;
cout << "This is base's vfunc().\n"; derived1 d1;
} derived2 d2;
}; f(b); // pass a base object to f()
class derived1 : public base { f(d1); // pass a derived1 object to f()
public: f(d2); // pass a derived2 object to f()
void vfunc() { return 0;
cout << "This is derived1's vfunc().\n"; }
}
};
class derived2 : public base {
public:
void vfunc() {
cout << "This is derived2's vfunc().\n";
}
};
Prepared by Dr. Naveen Choudhary 16
Virtual Attribute Inheritance
The virtual attribute is inherited : no matter how many times a virtual
function is inherited, it remains virtual.
int main()
#include <iostream>
{
using namespace std;
base *p, b;
class base {
derived1 d1;
public:
derived2 d2;
virtual void vfunc() {
// point to base
cout << "This is base's vfunc().\n";
p = &b;
}
p->vfunc(); // access base's vfunc()
};
// point to derived1
class derived1 : public base {
p = &d1;
public:
p->vfunc(); // access derived1's vfunc()
void vfunc() {
// point to derived2
cout << "This is derived1's vfunc().\n";
p = &d2;
}
p->vfunc(); // use derived1's vfunc()
};
return 0;
class derived2 : public derived1 {
}
public:
/* vfunc() not overridden by derived2.
In this case, since derived2 is derived from
derived1, derived1's vfunc() is used.
*/
}; Prepared by Dr. Naveen Choudhary 18
Pure Virtual Function
A pure virtual function is a virtual function that has no definition within the base class. To declare
pure virtual function, use this general form.
when a virtual function is made pure, any derived class must provide its own definition. if the
derived class fails to override the pure virtual function, a compile time error will result.
#include <iostream> class octtype : public number {
using namespace std; public:
class number { void show() {
protected: cout << oct << val << "\n";
int val; }
public: };
void setval(int i) { val = i; } int main()
virtual void show() = 0; // show() is a pure virtual function {
}; dectype d;
class hextype : public number { hextype h;
public: octtype o;
void show() { d.setval(20);
cout << hex << val << "\n"; d.show(); // displays 20 - decimal
} h.setval(20);
}; h.show(); // displays 14 - hexadecimal
class dectype : public number { o.setval(20);
public: o.show(); // displays 24 - octal
void show() { return 0;
cout << val << "\n"; }
}
}; Prepared by Dr. Naveen Choudhary 19
Abstract classes
A class that contains at-least one pure virtual function is said to be abstract. No object of
abstract class can be created
Using abstract class :: one interface - different action depending on slightly different (some
what similar) requirements
int main()
// Liters to gallons.
{
// Virtual function practical example. class l_to_g : public convert {
convert *p; // pointer to base class
#include <iostream> public:
l_to_g lgob(4);
using namespace std; l_to_g(double i) : convert(i) {}
f_to_c fcob(70);
class convert { void compute() {
// use virtual function mechanism to convert
protected: val2 = val1 / 3.7854;
p = &lgob;
double val1; // initial value }
cout << pgetinit() << " liters is ";
double val2; // converted value };
pcompute();
public: // Fahrenheit to Celsius
cout << pgetconv() << " gallons\n"; // l_to_g
convert(double i) { class f_to_c : public convert {
p = &fcob;
val1 = i; public:
cout << pgetinit() << " in Fahrenheit is ";
} f_to_c(double i) : convert(i) {}
pcompute();
double getconv() { return val2; } void compute() {
cout << pgetconv() << " Celsius\n"; // f_to_c
double getinit() { return val1; } val2 = (val1-32) / 1.8;
return 0;
virtual void compute() = 0; }
}
}; };
Prepared
by
Naveen Choudhary
Prepared by Dr. Naveen Choudhary 1
Templates
Template are used to create generic functions & classes int main()
Generic function - Same action (code) but different data
{
int i=10, j=20;
double x=10.1, y=23.3;
// Function template example. char a='x', b='z';
#include <iostream> cout << "Original i, j: " << i << ' ' << j << '\n';
using namespace std; cout << "Original x, y: " << x << ' ' << y << '\n';
// This is a function template. cout << "Original a, b: " << a << ' ' << b << '\n';
template <class X> void swapargs(X &a, X &b) swapargs(i, j); // swap integers
/* this statement tells the compiler two things that a swapargs(x, y); // swap floats
template is being created and a generic definition is swapargs(a, b); // swap chars
beginning */ // Note :- Because swapargs() is generic function,
//the compiler automatically creates three
//<class X> or you can write <typename X> in place of //versions of swapargs() one that will exchange
//<class X> //integer values, one that will exchange floating
// the above statement can also be written as under //point values, and one that will swap characters.
// template <class X> //1 cout << "Swapped i, j: " << i << ' ' << j << '\n';
// void swapargs(X &a, X &b) //2 cout << "Swapped x, y: " << x << ' ' << y << '\n';
// but nothing else should be there b/w statements 1 cout << "Swapped a, b: " << a << ' ' << b << '\n';
and 2 return 0;
{ }
X temp; note : the template function for a specific type
temp = a; will be generated when the compiler actually
a = b; encounters the call
b = temp; note that standard type conversion are not
} applied to function templates
Calls
2. myfunc(98.6,19L);
int main()
{
f(10); // calls f(X)
f(10, 20); // calls f(X, Y)
return 0;
}
Prepared by Dr. Naveen Choudhary 6
Using standard parameters with template
functions & Generic Classes
We can mix standard parameters with generic type parameters in a template function
Template <class X> void tabout (x data, int tab) { ----- }
Calls ::
Tabout (“this is a test”, 0)
Tabout(100,1)
Tabout (‘x’, 2)
Tabout(3.14, 3)
Note : generic functions are similar to overloaded functions except that they are more restrictive. When
function are overloaded, you may have different actions performed within the body of each function. But a
generic function must perform the same general action for all versions. Only the type of data can differ.
Generic classes
Note:- Member functions of a generic class are themselves automatically generic. you need not use template to
explicitly specify them as such
stack <addr> obj; //create a stack object obj. of user defined data
// type addr
Prepared by Dr. Naveen Choudhary 9
Two Generic Data Types -Example
/* This example uses two generic data types in a class definition. */
#include <iostream>
using namespace std;
template <class Type1, class Type2> class myclass {
Type1 i;
Type2 j;
public:
myclass(Type1 a, Type2 b) { i = a; j = b; }
void show() { cout << i << ' ' << j << '\n'; }
};
int main()
{
myclass<int, double> ob1(10, 0.23);
myclass<char, char *> ob2('X', "Templates add power.");
ob1.show(); // show int, double
ob2.show(); // show char, char *
return 0;
}
Prepared by Dr. Naveen Choudhary 10
Using non-type arguments with generic classes
In the template specification for a generic class, you may specify non-
type arguments also
Call:-
type <int, 10> intob; //integer array of size = 10
type <double, 15> dob; // double array of size = 15
Note:- The arguments that you pass to a non-type parameter must
consist of either an integer constant, (no float can be non type argument)
or a pointer or reference to a global function or object. & thus there
values inside the class's function can't be changed. Why because The
information contained in non –type arguments must be known at compile
time. these non-type parameters should themselves be thought as
constants.
Prepared by Dr. Naveen Choudhary 11
Using default arguments with template classes
Calls:-
atype <int, 100> intarray; // integer array , size 100
}
. 4. Any type of data can be caught i.e. build in data type & even user defined class
.
catch(typeN arg) { 5. In general, catch expression are checked in the order in which they occur in a
//catch block program & only the matching catch is executed and all other catch are ignored
}
You can have a throw exception :: statement with in the try block to throw the exception manually
If there is no corresponding catch block then standard library function terminate () will be invoked. By default
terminate () calls abort () to stop your program.
Two Ways :
Using ios member function :- Using ios member function & setting status flags of
ios class using the member function
Using manipulators :- These are special functions that can be included as part of
the I/O expression
boolalpha When set, Booleans can be input or output using the keyboard True or False
showbase Use base indicator on output ( o for Octal, 0x for Hex ) -- on/off flag
showpoint Show decimal point on output (ie causes a decimal point & trailing zeros to be displayed
for all floating point output whether needed or not) -- -- on/off flag
uppercase By default, when scientific notation is displayed, the e is in lowercase. Also when a
hexadecimal value is displayed, the x is in lower case. When uppercase is set, these
characters are displayed in uppercase -- on/off flag
showpos Display + before positive intergers -- -- on/off flag
unitbuf When unitbuf is set, the buffer is flushed after each insertion operation -- on/off flag
basefield Oct, Dec & Hex fields are collectively called basefield
Fixed Use fixed notation for printing float values Note that manipulators affect only the data
Internal Use padding between sign or base indicator that follows them in the stream, not the
and value data that precedes them. Table
Left Left align, pad on right summarizes the important manipulators
Noshowbase Turns off showbase flag Output that take arguments. You need the
IOMANIP header file for these function.
Noshowpoint Do not Show decimal point Prepared
& trailing zeros
by Dr. Naveen Choudhary 12
for float values # include <iomanip.h>
Table
ios Manipulators with Arguments Example –2 (skip)
Manipulators Arguments Purpose
#include <iostream>
#include <iomanip>
setw (int ) Field width (int) Set field width for using namespace std;
output int main()
setfill (int ) Fill character Set fill character for {
(int) output (default is space)
cout.setf(ios::hex, ios::basefield);
setprecision (int ) Precision (int) Set precision (number of cout << 100 << "\n"; // 100 in hex ie 64
digits displayed after
decimal point) cout.fill('?');
setiosflags (long) Formatting flags Set format flags
cout.width(10);
(long) specified by n. setting cout << 2343.0;
remains in effect until // cout << 1232.0 now fill() & width()
next change
//will not be applicable here
resetiosflags Formatting flags Clear specified flags. return 0;
(long) (long) setting remains in effect
until next change }
setbase (int ) Base (int) Set the no. base to base (
Example –3 (SKIP )
0 – base 10, 8 – octol, 16 #include <iostream>
– hex ) #include <iomanip>
Example –1 using namespace std;
#include <iostream> int main()
#include <iomanip> {
using namespace std;
int main() cout << setiosflags(ios::showpos);
{ cout << setiosflags(ios::showbase);
cout << hex << 100 << endl;//64 cout << 123 << " " << hex << 123;//
cout << setfill('?') << setw(10) << 2343.0;//??????2343
return 0;} Prepared by Dr. Naveen Choudhary //+123 0x7b 13
return 0;}
#include<iostream.h>
#include <conio.h> resetiosflags ( ios::showpos )
#include <iomanip.h> «endl«a; //425.000000
void main( ) cout « resetiosflags ( ios::showpoint )
{ «endl«a; //425
int i=52; cout « setiosflags ( ios::fixed ) « endl « b ; //123.500328
float a = 425.0 ; cout « setiosflags ( ios::scientific ) « endl « b ;
float b = 123.500328 ; //1.235003E+02
char str[ ] = "Dream. Then make it happen!" ; b = 5.375 ;
clrscr( ) ; cout.precision ( 14 ) ;
cout « setiosflags ( ios::unitbuf | ios::stdio | ios::showpos ) cout « setiosflags ( ios::fixed ) « endl « b ; // 5.375
; cout « setiosflags ( ios::scientific ) « endl « b ;
cout« I «endl; // +52 //5.375E+00
cout « setiosflags ( ios::showbase | ios::uppercase ) ; cout « resetiosflags ( ios::showpoint | ios::unitbuf |
cout « hex « i « endl ; // 0X34 ios:stdio ) ;
cout « oct « i « endl ; // O64 }
cout « setfill ( '0' ) ;
cout « "Fill character:" « cout.fill( ) « endl ;//0
cout«dec«setw(10)«i«endl; // 0000000+52
cout « setiosflags ( ios::left)
«dec «setw(10)«i«endl; // +520000000
cout « setiosflags ( ios::internal )
«dec«setw(10)«i«endl; // +000000052
cout « i « endl ; // +52
cout « setw (10 ) « str « endl ; // dream.then make it happen
cout « setw ( 30 ) « str « endl ;//00000dream.then make it
//happen
cout « setiosflags ( ios::left ) « setw ( 40 ) « str « endl ;
//dream.then make it happen00000
cout«precision ( 6 ) ;
cout « "Precision: " « cout.precision( ) ; // +6
cout « setiosflags ( ios::showpoint ) « Prepared by Dr. Naveen Choudhary 14
Example –4
Example –4 #include <iostream>
#include <iostream> #include <cstring>
using namespace std; using namespace std;
int main() class phonebook {
{ public:
bool b; char name[80];
b = true; int areacode;
cout << b << " " <<boolalpha<< b << endl; // int prefix;
1 true int num;
cout << "Enter a Boolean value: ";//false phonebook(char *n, int a, int p, int nm)
cin >> boolalpha >> b; {
cout << "Here is what you entered:"<<b; strcpy(name, n);
//false areacode = a;
return 0; prefix = p;
} num = nm;
Overloading << & >> (insertion & }
};
extraction operator ) // Display name and phone number.
Inserter overloading ostream &operator<<(ostream &stream,
phonebook o) // can not be member function of
ostream & operator << ( ostream &stream,
//phonebook
class_type obj) {
{ stream << o.name << " ";
//body of inserter stream << "(" << o.areacode << ") ";
return stream; Prepared by Dr. Naveenstream << o.prefix << "-" << o.num << "\n"; 15
Choudhary
} return stream; } // must return stream
#include <iostream>
int main() #include <cstring>
{ using namespace std;
phonebook a("Ted", 111, 555, 1234); class phonebook {
phonebook b("Alice", 312, 555, 5768); // now private
phonebook c("Tom", 212, 555, 9991); char name[80];
cout << a << b << c; int areacode;
return 0; int prefix;
} int num;
public:
In the preceding program, notice that phonebook(char *n, int a, int p, int nm)
the phone book, inserter is not a {
member of phone book and it can not strcpy(name, n);
be as left side of the << operator is areacode = a;
stream and not the phonebook class prefix = p;
Beside 1st argument must be of type num = nm;
ostream & not of phone book. }
friend ostream &operator<<(ostream
But if inserter operator is not a member &stream, phonebook o);
function then we can’t access the private };
members of the class phonebook in the // Display name and phone number.
overloaded inserter operator. ostream &operator<<(ostream &stream,
Solution : make the inserter operator phonebook o)
function , friend of the phonebook {
class. stream << o.name << " ";
Prepared by Dr. Naveen Choudhary 16
stream << "(" << o.areacode << ") ";
stream << o.prefix << "-" << o.num << "\n"; Example
return stream; // must return stream #include <iostream>
} #include <cstring>
int main() using namespace std;
{ class phonebook {
phonebook a("Ted", 111, 555, 1234); char name[80];
phonebook b("Alice", 312, 555, 5768); int areacode;
phonebook c("Tom", 212, 555, 9991); int prefix;
cout << a << b << c; int num;
return 0; public:
} phonebook() { };
phonebook(char *n, int a, int p, int nm)
Inside inserter operator we have used: {
1. stream << o.name << “ ”; strcpy(name, n);
we could have also used
2. cout << o.name << “ ”;
areacode = a;
but 1 is more generic & can be used with any prefix = p;
ostream. Whereas 2 can only be used with cout. num = nm;
}
Overloading extractor operator friend ostream &operator<<(ostream
istream & operator >> (istream & stream, &stream, phonebook o);
class_type &obj) friend istream &operator>>(istream
{ &stream, phonebook &o);
//body of extractor };
return streanm;
} Prepared by Dr. Naveen Choudhary 17
// Display name and phone number.
ostream &operator<<(ostream &stream, (skip) Actually extractor operator defined
phonebook o) in the previous example is not correct. If
{ istream is cin then ok but if istream is
stream << o.name << " "; some disk file then we should not use cout
stream << "(" << o.areacode << ") "; (as we have used in the example).
stream << o.prefix << "-" << o.num << "\n";
return stream; // must return stream Creating your own
} manipulator function
// Input name and telephone number.
istream &operator>>(istream &stream, Manipulator can be with parameter or
phonebook &o) parameterless.
{
cout << "Enter name: "; stream >> o.name; 1. Parameterized manipulators can take
cout << "Enter area code: "; some argument in addition to istream/
stream >> o.areacode; ostream.
cout << "Enter prefix: "; stream >> o.prefix; 2. //(skip) Parameterless manipulators can
cout << "Enter number: "; stream >> o.num; take only a single argument which is of
cout << "\n"; type istream/ ostream.
return stream; 3. //(skip) creating customized
} parameterized manipulators is compiler
int main() dependent & you need to go through,
{ the compiler documentation. So these
phonebook a; type of manipulators are not further
cin >> a; cout << a; discussed.
Prepared by Dr. Naveen Choudhary 18
return 0;}
4. O/P manipulators
ostream & manip_name(ostream
Example-1(skip)
&stream)
#include <iostream>
{
#include <iomanip>
// your code here
using namespace std;
}
// A simple output manipulator.
istream & manip_name (istream &
ostream &sethex(ostream &stream)
stream)
{
{
stream.setf(ios::showbase);
// your code here
stream.setf(ios::hex, ios::basefield);
}
return stream;
}
The call to these manipulators is from the
int main()
insertion/ extraction operation as shown
{
below & we need not pass arguments
cout << 256 << " " << sethex << 256;
during the call.
return 0;
}
cout << 256 << “ ” << sethex <<256;
Or
cin>> getpass >> pw
After creating file streams, you need to associate these stream to files with the help
of open ().
void ifstream::open (const char *filename, ios::openmode) ios::in (default)
void ofstream::open (const char *filename, ios::openmode) ios::out | ios::trunc (default)
void fstream::open(const char *filename, ios::openmode) ios::in | ios::out (default)
modes
ios::app - Append to the end of file
ios::ate - File offset is set to the end of the file, although I/O
operation are allowed to occur anywhere in file.
ios::in - File capable of input
ios::out - File capable of output
ios::trunc - If the named file already exist, the file is destroyed & is truncated to
zero length.
ios::binary- ios::binary value causes a file to be opened in binary mode. By
default, all files are opened in text mode. In text mode the file store information as
character (like 439) will be stored as these characters ‘4’,’3’,’9’ moreover various character
translation may take place such as carriage return/ linefeed sequence being converted
into newlines. However when a file is opened in binary mode, no such character
translation will occur (also bytes in memory will be stored as it is in the file like if 257 =
0000000100000001 in memory will be stored
Prepared as it isChoudhary
by Dr. Naveen in the file. 25
Note :: Any file, whether it contains formatted text or raw data, can be opened in
either binary or text mode.
ofstream out;
out.open (“test”, ios::out); //out.open (“test”); as ios::out is default for ofstream.
To close out.close()
If open ( ) fails, the stream will evaluated to false when used in a Boolean
expression.
if (!mystream)
{
cout<<”cannot open file\n”; //handle error
}
The ifstream, ofstream & fstream classes have constructor function that automatically
open the file. The constructor function have the same parameters & defaults as the
open ( ) function.
You can also check to see if you have successfully opened a file by using
the is_open ( ) function, which is a member of fstream, ifstream ofstream.
1. read characters into array pointed by buf until similar to 1 but the new line character is
num-1 characters have been read or newline is
extracted from the stream but is not put into buf
found or the end of the file has been
encountered. The array pointed to by buf will be (i.e. it is basically removed)
NULL terminated by get(). If the newline
character is encountered in the input stream, it is istream &getline (char *buf, streamsize num, char delim)
not extracted, instead, it remains in the stream
until the next input operation. similar to 2 but the delim char is extracted from the
stream but is not put into buf (i.e. it is basically removed)
2. reads char until num -1 characters have been
read or char specified by delim has been found
or the end of the file has been encountered. buf
will be NULL terminated. If the delim char is
encountered in the input stream, it is not
extracted.
ifstream infile(sourcefile);
xyz.exe ofstream outfile(targetfile);
outfile << infile.rdbuf();
(1) this causes the entire contents of the source file to be
To open a file for read as well as write use File.open
(“EMP.DAT”, ios::binary |ios::in |ios::out); sent to the outfile/targetfile
The following program prints the contents of a disk file on the printer.
After printing the entire file contents a ‘\x0c’ is sent to the printer to
eject the paper
Ofstream outfile(“PRN”);
While (infile.get(ch) !=0) // ifstream infile(filename)
Outfile.put(ch)
Outfile.put(‘\x0C’);