[go: up one dir, main page]

0% found this document useful (0 votes)
30 views155 pages

CHP 3 C++

Uploaded by

nhbinaaa112
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views155 pages

CHP 3 C++

Uploaded by

nhbinaaa112
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 155

Chapter 3 C++

References
• The reference feature of C++ is related to
pointer.
• A reference is an implicit pointer.
• A reference can be:
1) As a standalone(independent) reference.
2) A function parameter
3) As a function return value
1) Independent Reference
• we can create independent reference, that is
reference variable.
• They must be initialized at the time of
declaration.
• Ex: float total=100;
float &sum=total;
2) Reference parameters
• Arguments can be passed to function.
• There are two ways to achieve call be reference
1) Explicitly pass a pointer to argument
2) Use reference parameter
void minus(int &i);
void main()
{
int x;
x=10;
cout<<x;
minus(x);
cout<<x;
}
void minus(int &i)
{
i=-i;
}
3) Returning reference
• A function may return a reference.
• It allows the function to be used on the left
side of an assignment statement.
• Ex:
replace(5)=‘x’

Generally
x=replace(5)
#include<iostream.h>
char & replace (int i);
char s[80]=“hello Brother”;
void main()
{
replace(5)=‘x’;
cout<<s;
}
char & replace(int i)
{
return s[i];
}
char &replace(int i);
char s[80]="hello Brother";
void main()
{
clrscr();
int i;
char c;
cout<<"enter a what position you want to replace";
cin>>i;
cout<<"\n enter the character to be replaced";
cin>>c;
replace(i)=c;
cout<<s;
getch();
}
char &replace(int i)
{
return s[i];
Strings:
• Strings are 1dim array of char datatype.
• String constants are written in double quotes.
• A string is terminated by a null character i.e ‘\
0’

• Ex: “length” is a string of 7 and last character


is null.
C++ program to read a line from keyboard and display it.

#define MAX 80
#include<iostream.h>
#include<conio.h>
void main()
{
char line[MAX];
cout<<“\n enter a line of text \n”;
cin.getline(line,max,’\n’);
cout<<line;
}
String Functions
• C++ complier has a large set of useful string
handling library functions.
• These functions are in string.h header file.
1) strlen()
2) strcpy()
3) strcat()
4) strcmp()
strlen():
• this function counts number of characters in the string
void main()
{
char arr[ ]=“hello”; Output
int len1,len2; 5 3
len1=strlen(arr);
len2=strlen(“hii”);
cout<<len1<<“ \t” <<len2;
}
strcpy()
• This function copies the source string to the
target string.
• Ex: strcpy(target , source);
void main()
{
char s[]=“praveen”;
char t[30];
strcpy(t,s);
cout<<t<<s;
} praveen praveen
strcat()
• This function concatenates the source string at
the end of the target string.
• Ex: strcat(target , source);
void main()
{
char s[]=“praveen”;
char t[]=“khanale”;
strcat(t,s);
cout<<t;
} khanale praveen
strcmp()
• This function compares two strings to find out
whether they are same or different.
• The two string are compared character by
characters until there is a mismatch.
• Or end of one of the string.
• 1) if both are identical, function returns 0
• 2) else returns the numeric difference
between them(ASCII value).
Output
0 -8
void main()
{
char s1[]=“Narendra”;
char s2[]=“Virendra”;
int i,j;
i=strcmp(s1,”Narendra”);
j=strcmp(s1,s2);
cout<<i<<“\t”<<j;
}
Array

• C++ program to read a set of numbers from


keyboard and find largest number in the given
array.
#include<iostream.h>
#include<conio.h>
void main()
{
int large, i,n, a[50];
cout<<“How many numbers?”;
cin>>n;
for(i=0;i<n;i++)
Large=a[0];
for(i=0;i<n;i++)
{
if(large<a[i])
{
large=a[i];
}
}
cout<<“largest value is”<<large;
getch();
}
Array and function
• The entire array can be passed onto a function
in C++.
• An array name can be used as an argument for
the function declaration.
• NO subscript brackets are required to invoke a
function using array.
• For example:
• Int sumarray(int a[20], int n) //definition

• Sum=sumarray(a,n) //function call


#define max 10
#include<iostream.h>
#include<conio.h>
void output(float a[max][max],int n);
Void mul(float a[max][max], float b[max][max],int n);
void main()
{
float a[max][max], b[max][max];
int i,j,n;
cout<<“enter n matrix”
cin>>n;
cout<<“enter elements in matrix a”
for(i=0;i<n;i++)
{
for (j=o;j<n;j++)
{ cin>>a[i][j]; }
cout<<“enter elements of matrix b”;
for(i=0;i<n;i++)
{
for (j=o;j<n;j++)
{ cin>>b[i][j]; }
}
cout<<“A matrix: \n”;
output(a,n);
cout<<“B matrix:\n”;
output(b,n);
mul(a,b,n);
getch();
}
void output(float x[max][max],int n)
{
float i,j;
for(i=0;i<n;i++)
{
for (j=0;j<n;j++)
{
cout<<x[i][j]<<“\t”;
}
cout<<“\n”;
}
}
void mul(float a[max][max], b[max][max],int n)
A B
{ 0 1
0 1
float c[max][max],i,j,k;
for(i=0;i<n;i++) 0 1 2 0 1 1
11 11
{ 1 2 3 1 1 1
for (j=0;j<n;j++)
{
c[i][j]=0+a[0][0]*b[0][0])
c[i][j]=0.0; 0+1*1
for (k=0;k<n;k++) =1
{ C
c[i][j]=c[i][j]+(a[i][k]*b[k][j]); 0 1

} 0
0 0
} 11
1 0 0
}
cout<<“C Matrix: \n”;
output(c,n);
#include<iostream.h>
class date
{ private:
int day,month,year;
public:
void getdata()
{
cout<<“\n enter date”;
cin>> day>>month>>year;
}
void display()
{
cout<<“today’s date is”<<day<<“/”<<month<<“/”<<year;
}
};
void main()
{
clrscr();
date d; //date d,d2;
d.getdata();
d.display();
date d2;
d2.getdata();
d2.display();
getch();
}
Principle of Object Oriented Programming
• In OOP, the program is designed around the
data being operated upon rather than the
operation.
• It bind the data to the function.
• OOP allows us to break(decompose) a
problem into number of objects.
• And then build data and function around it.
Object A
Data
Object B Function
Object C
Data
Function Data
Function
Features of OOPS are
1) Emphasis is on data rather than procedure.
2) Programs are divided into objects.
3) Every object has its own data and function.
4) The data can be accessed by function associated with
that object.
5) Data are hidden and cannot be accessed by external
functions.
6) Object may communicate with each other through
function.
7) New data & function can be easily added.
8) Follows bottom up approach.
Objects:
• Objects are basic run –time entities in OOPs
• Object can represent a person, place, a bank
account, table of data, etc.
Object: Student s1
DATA:
char name[30];
int marks;
char DOB[10];
……………….

Functions:
int TOTAl(int m1,int m2);
int average();
……………………….
Classes:
• Object are created based on class.
• Object contain data and code to manipulate
that data.
• Class is a user-defined data type.
• Objects are variable of class.
• Ex: int a; char b;
similarly person p1, p2;
complex c1,c2;
fruit apple,mango;
• Inheritance:
• Inheritance is a process by which we can built
new classes from old ones.
• The new class is called as derived class and old
class is known as Base class.
• New class inherits the data structure and
functions.
• Ex:
birds class
flying birds non flying birds
• Polymorphism:
• Means the ability to take more than one
forms.
• Single function name can be able to handle
different no. of arguments and different
datatype.

• Ex: ‘+’ when taken with integer number will


add them.
• ‘+’ with strings will concatenate them.
Classes and Objects
• A class is a way to bind data and its associated
function together.
• It allows data to be hidden from external use.
• A class specification has 2 parts:
1) Class declaration
2) Class function definitions.

Class declaration describes the type and scope of its


members.
class class_name
{
private:
variable declaration;
function declaration;
public:
variable declaration;
function declaration;
};
#include<iostream.h>
class xyz
{
public:
void getdata();
};
void xyz::getdata()
{
}
void main()
{
xyz x1;
x1.getdata()
• Private:
members that are declared as private can be accessed
only from within the class.

• Public:
public members can be accessed from outside the
class.

Default value is private.


Terms :
1) Data abstraction.
2) Data hiding
3) Data encapsulation.
Data abstraction
1) Abstraction refers to the act of representing features without
including background details.
2) Classes are concept of abstraction. Defined as a list of
attributes and functions.
3) They encapsulate all the essential properties of the object
that are to be created.
Ex: class product_item
{ private:
int number;
float cost;
public:
void getdata(int a,int b);
void putdata();
• Once class is declared, we can create variables
of that type.
• product_item x;
• These class variables are known as object.
• i.e object of type product_item.
• At declaration, memory is created for object.
• More than 1 objects like,
product_item x, x1, x2;
• Private data of class can be accessed by its
member function only.
• Main() function cannot access then directly.
• From main() ,public members can be accessed.

• The general form for calling a member function is:


objectname.functionname(actual argument)
ex: x. getdata(100,75.5);
x.putdata();
#include<iostream.h>
class date
{
int day,month,year;
public:
void getdata()
{
cout<<“\n enter date”;
cin>> day>>month>>year;
}
void display()
{
cout<<“today’s date is”<<day<<“/”<<month<<“/”<<year;
}
};
void main()
{
clrscr();
date d;
d.getdata();
d.display();
getch();
}
Defining Member Functions
• Member function can be defined in two
places:
1) Outside the class definition
2) Inside the class definition.
Outside the class definition
Member Function which are not defined inside the class
has to be defined separately outside the class.
return_type classname:: functionname(argu)
{
functions body
}
Ex: void xyz::getdata(int a,int b)
{
x=a;
y=b;
}
Inside the class definition
• A member function can be defined inside a class.
• For example:
class xyz
{
public:
void getdata(int a,int b)
{
x=a;
y=b;
}
Memory allocation for objects
• The memory space for member functions is
allocated when they are defined as a part of
class.
• All object of same class uses same memory
functions.
• Separate memory for object when they are
declared.
Common for all object
Member functions 1

Member functions 2

OBJECT 1
Member variable 1
OBJECT 2
Member variable 1

Member variable 2
Member variable 2
Static data members
• A data member of a class can be qualified as static.
• Static member variable has following characteristic
1) It is initialized to zero when first object of its class is created. (no
initialization is permitted)
2) Only one copy of that member is created for entire class and
shared by all objects.(no matter how many object is created)
3) It is visible only within the class, but its life time is the entire
program.
Used normally to maintain values common to either class.
Ex: class item
{
static int count;
------
}
Static member functions
• A member function which is declared as static has the
following properties:
1) A static function can have access to only other static
members(functions or variable) declared in same
class.
2) A static member function can be called using the class
name(instead its objects)
3) Class_name::function_name;
Ex: class test
{ static void showcount();
}
test::showcount(); //X
Array of Objects
• We can have array of variables that are of type
class.
• Such variables are called array of objects.
Ex:
class employee
{
int emp;
};
employee manager[5]; //array of manager.
employee worker[50];//array of worker.
#include<iostream.h>
class student
{ int rollno,age;
char gender;
float height,weight;
public:
void getinfo()
{
cout<<“enter roll no and age”;
cin>>rollno>>age;
cout<<“\n enter gender”;
cin>>gender;
cout<<“\n enter height and weight”;
cin>>height>>weight;
}
void display()
{
cout<<“roll no”<<rollno<<“\n age=“<<age;
cout<<“gender=“<<gender;
cout<<“height=“<<height<<“\n weight=“<<weight;
}
void main()
{
student obj[100]; //array of object
int i,n;
cout<<“\n enter how many student”;
cin>>n;
cout<<“\n enter information”;
for(i=0;i<n;++)
{
cout<<“record=“<<i+1;
obj[i].getinfo();
}
cout<<“\n content of class is”;
for(i=0;i<n;++)
{
obj[i].display();
}
Write a program in c++ to solve quadratic equation using
OOP technique
#include<iostream.h>
#include<math.h>
class equation
{
float a,b,c;
public: void getinfo(float aa,float bb,float cc);
void display();
void equal(float aa,float bb);
void imag();
void real(float aa,float bb, float det);
};
void equation::getinfo(float aa,float bb,float cc)
{ a=aa;
b=bb;
c=cc; }
void equation::display()
{
cout<<“a=“<<a;
cout<<“b=“<<b;
cout<<“c=“<<c;
}
void equation:: equal(float a,float b)
{
float x=-b/(2*a);
cout<<“\n roots are equal=“<<x;
}
void equation::imag()
{
cout<<“roots are imaginary”;
void equation::real(float aa,float bb,float det)
{ float x1,x2,temp;
temp=sqrt(det);
x1=(-b+temp)/2*a;
x2=(-b-temp)/2*a;
cout<<“\n roots are real:\n”;
cout<<“x1=“<<x1;
cout<<“x2=“<<x2;
}
void main()
{
equation equ;
float aa,bb,cc;
cout<<“\n enter three numbers”;
cin>>a>>b>>c;
equ.getinfo(aa,bb,cc);
equ.display();
if(aa==0)
{ float temp=cc/bb;
cout<<“\n linear roots=“<<temp;
}
else
{
float det;
det=bb*bb-4*aa*cc;
if(det==0)
{ equ.equal(aa,bb); }
else if(det<0)
{ equ.imag(); }
else
{
equ.real(aa,bb,det);
}
}
getch();
Objects as function arguments
• Object can be used as function arguments.
• Done in 2 ways:
1) Pass by Value
(A copy of the entire object is passed.
changes are temporary)
2)Pass by reference.
(Address of object is transferred to functions.
changes are permanent)
Friendly functions
• Private data not be accessed.
• There can be situation where we would like two classes to share
a functions.
• That function can be made friend of both classes.
• Function can then access both private data.
• Such function need not be member of a class.
• We need to declare it as friend.
• Ex: friend void display();
• Function is written outside like a normal program.
• The function can be declared as a friend in any number of classes.
Constructors and destructors
• A constructor is a special member function for automatic
initialization of an object.
• Constructor is executed automatically when an object is
created.
• It is used to initialize data members.
• Hence called constructor.

Syntax rules for writing constructor are:


1) Name must be same as class name
2) It is declared with no return type.
3) It may not be static or virtual.
4) It should be public. Only in rare circumstance it can be private.
class user_name
{
private:

public:
user_name(); //constructor
};
User_name::user_name() //constructor
defined
{
}
Write a program to display Fibonacci number
using constructor.
class Fibonacci
{
long fo,f1,fib;
public:
Fibonacci();
void increment();
void display();
};
Fibonacci:: Fibonacci(int a, int b))
{
f0=a;
f1=b;
fib=f0+f1;
}
Fibonnaci::fibonnacee()
{}
Fibonacci::display()
{
cout<<fib<<“\t”;
}
Void Fibonacci::increment()
{
f0=f1;
f1=fib;
fib=f0+f1;
void main()
{
Fibonacci n(0,1);
cout<<“0 , 1“;
for(int i=0;i<=15;i++)
{
n.display();
n.increment();
}
getch();
}
Parameterized constructors
• It is possible to pass arguments(parameters) to the
constructor function when the objects is created.
• These constructors are called as parameterized
constructor
ex:
class number
{
public:
number(int x,int y);
}
Multiple constructor in a class
• C++ permits us to use more than one constructor in
same class.
• Ex:
class number
{
number();
number(int a);
number(int a,int b);
}

Number i1, i2(5), i3(3,4);


Constructor with default arguments
• Ex: complex(float real, float imag=0);

So, complex c1(5.0);


Else complex c2(5.0,7.8);
The actual parameter, when specified will
overwrite the default value.
Copy constructor
• Are always used when the complier has to create a
temporary object of class object.
• Used in situation as
1: the initialization of object by another object of same
class.
2. Return of object as by value parameter of function.
3. Stating the object as by value parameter of a function.
Class name:: class-name(class name & ptr)
Ex: x::x(x &ptr);
Ptr is pointer of x class.
Ex: X i1, i2(i1);
destructor
• Is a function that automatically executed when an
object is destroyed.
• Or scope ends(out of existence)
• Usage of destructor is to release space from heap of
memory.
• A destructor can also be invoked explicitly.
• Rules:
1) Name is same as class but first character is ~(tidle)
2) No return type.(it cannot return a value)
3) It takes no argument.
• Syntax:
class user_name
{
public:
user_name(); //constructor
~ user_name(); //destructor
};
Program to demonstrate destructor

class account
{
float balance, rate;
public:
account(); //constructor
~account(); //destructor
void deposit();
void withdraw();
void compound();
void getbalance();
void menu();
Dynamic initialization of objects
Class objects can be dynamically initialized.
i.e. put values during runtime.
Ex: constru ob1,ob2(2,4),//ob2;
or
ob2=constru(a,b);
Adv.: provides flexibility of using different format
and value.
Use dynamic initialization and default constructor

class fixed_deposit
{
int p_amount,year;
float rate,r_value;
public:
fixed_deposit() {}
fixed_deposit(int p,int y,float r=0.12);
fixed_deposit(int p,int y,int r);
void display();
};
void main()
{
fixed_deposit fd1,fd2,fd3;
int p,y,R;
float r;
cout<<“enter amount,period,rate(percent)”;
cin>>p>>y>>R;
fd1=fixed_deposit(p,y,R); //dynamic
cout<<“enter amount,period,rate(decimal)”;
cin>>p>>y>>r;
fd2=fixed_deposit(p,y,r); //dynamic
cout<<“enter amount,period”;
cin>>p>>y;
fd3=fixed_deposit(p,y); // default constructor
Inheritance
• Stands for derivation.
• The mechanism of deriving a new class from
on old one is called inheritance.
• Old class – BASE class
• New class- DERIVED class.
1) Single Inheritance: A

2) Multiple Inheritance A B

3) Hierarchical inheritance
A

B C D
4) Multilevel inheritance A

5) Hybrid Inheritance A

B C

D
• Defining deriver classes
Syntax:

class derived_classname : visibilitymode baseclass


{
//members of derived class

}
Ex: class test: public student
{

}
Single inheritance
• Write a program in C++ to create class index having increment
facility, using inheritance create another class index1 having
decrement facility.

class index //base clas


{ protected:
int count;
public:
index() { count =0; }
index(int c) { count =c; }
void display() { cout<<“count=“<<count;
void operator ++()
{
count++;
}
class index1 : public index //derived class
{
public:
friend void operator -- (index c)
{
c.count--; }
};
void main()
{
index1 i;
i++;
i++;
i.display();
i - -;
i.display();
getch();
Visibility of inherited members
Base class Derived class visibility
visibility
Public Private Protected
derivation derivation derivation
Private Not Not Not
inherited inherited inherited
Protected protected Private Protected
Public Public Private protected

Ex: class derived : public base


Multilevel inheritance
class student
{
};
class test: public student
{
};
class result: public test
{
};
Multiple inheritance
Syntax:
class D : public A , public B,…
{
members of D;
}
Hierarchical inheritance
class student
{ };
Class test: public student
{ };
class sports: public student
{ };
class abc : public student
{ };
GP
Virtual base class P1 P2

CHILD
• When all inheritance are involved.
• Here child has 2 direct base. Which
themselves has common base.
• So child would have duplicated sets of
members from GP.
• Resulting in ambiguity.
• It can be avoided.(By making the common
base class as virtual base class)
class GP
{};
class p1 : virtual public GP
{};
class P2 : virtual public GP
{};
class child: public p1,public p2
{};
Only one copy of that class is inherited,
regardless of many inheritance paths.
Abstract class
• An abstract class is one that is not used to
create objects.
• It is designed only to act as a base class.
• Which will be inherited by other classes.
• This is a designed concept in program
development.
Constructors in derived classes
• If a base class contains constructor with 1 or
more arguments,
• then it is mandatory for derived class to have
constructor and pass arguments to base class
constructor.

• When both contains constructor,


• Base constructor is executed first and then of
derived class.
Nesting of classes
• When a class contains object of another class as its member
then it is called nesting of class.
• Ex:
class alpha
{ };
class beta
{
alpha a; // a is object of alpha class
};
This is another way of inheriting properties on one class into
another,
Operating overloading
• C++ permits us to add 2 variables of user
defined data type.
• C++ has ability to provide the operator with
special meaning.
• The Mechanism of giving such special
meaning to an operator is known as operator
overloading.
• Overloading stands for giving additional
meaning to.
• We cannot overload following operators:
1) Class member access operator( . And .*);
2) Scope resolution (::)
3) Sizeof()
Conditional operator( :?)
Even if we overload an operator , original
meaning never changes.
Defining operator overloading
We must specify what it means in relation to the class.
Its done with an operator functions.
Syntax:
Returntype classname :: operator op-to-be(argulist)
{
function body;
return statement;
}
• Operator function can be either member or
friend functions.
• Only those operator that are predefined in c++
can be overloaded.
• Ex: void operator ++();
Void operator -(int x);
Steps:
1) Create a class that defines the datatype that
is to be used in overloading operation.
2) Declare operator functions in public part of
class.
it may be member or friend function.
3) Define the operator function to implement
the required operations.
Member function Friend function
For unary: no argument For unary : 1 argument
For binary: 1 argument For binary: 2 argument

Calling or invoking: Calling or invoking:


Unary: op x or x op Unary: op(x)
Binary: x op y Binary: x.operator op(y)
operator op(x,y)

Ex: +a or a+ Ex: +(a)


a+b opeartor +(a,b)
To overload unary minus
class space
{ int x,y,z;
public:
void getdata(int a,int b,int c)
{
x=a;y=b;z=c;
}
void display()
{
cout<<x<<“ ”<<y<<“ ”<<z;
}
Output
Void operator –()
{ S: 10 -20 30
S1: -10 20 -30
x=-x;
y=-y;
z=-z;
}
};
Void main()
{ space s;
s.getdata(10,-20,30);
c.display()
-s; //activates operator –
cout<<“s:”;
s.display();
Overloading binary operator
class complex
{ float real,imag;
public:
complex() {}
complex(float r,float i)
{ real=r;
imag=i;
}
void display()
{ cout<<real<<“+i”<<imag; }
complex operator +(complex b)
{
complex t;
t.real=real+b.real;
t.imag=imag+b.imag;
return (t);
}
};
void main()
{
complex c1,c2,c3;// c1(2,5),c2(3,5)
c1=complex(2.5,3);
c2=complex(1.1,2.3);
c3=c1+c2;
cout<<“ c1=“<<c1.display();
cout<<“ c2=“<<c2.display();
cout<<“ c3=“<<c3.display();
Rules for overloading
• Only existing operator can be overloaded.
• New cannot be created.
• Overload Operator must have at least one operand as user
defined type.
• We cannot change the basic meaning of the operator.
• Certain operators cannot be overload( ., ::,?:, sizeof)
• Certain operators cannot be overloaded by friend function(=,(),
[],->)
• Unary operator as member function-> no argument
• Binary operator as member function-> 1 argument
• Unary operator as friend function-> 1 argument
• Binary operator as friend function-> 2 argument Binary operators
=,-,*,/ must return a value.
Virtual function and
polymorphism
Virtual functions and polymorphism
• Polymorphism stands for many forms.
• C++ refers to identical named functions to behave in
differently depending on the type of object they
refer.
• Compile->Early binding/static binding/ static linking
• Runtime-> dynamic binding
Class a
{ int x;
public:
void show() {}
void add() {}
void add(int a) {}
};
Class b : public a
{ int y;
public void show() {}
};
Compile time polymorphism

when the compiler known about the function


definition at compile time.

complier can point to respective function when


called from main function.

its known as early binding and also known as


static binding.
Run time polymorphism

it when the compiler does not known about the


function definition at compile time.

complier cannot point to which function when


called from main function.

its known as late binding and also known as


dynamic binding.
void add(int )
void add(int,int) // for complier its function
Int add(int) overloading

void print() // not function overloading


void print() // its overridding
class A
{
int x;
public:
void show() {}
};
class B
{
int y;
public:
void show() {}
};
POLYMORPHISM

COMPILE TIME RUN TIME


POLYMORPHISM POLYMORPHISM

FUNCTION OPERATOR
VIRTUAL FUNCTION
OVERLOADING OVERLOADING
Pointer to object
A pointer can point to an object created by class
Example :
Int A; B b; // B is a class and b is object
Int *ptr
B *ptr //ptr is pointer to type B
Ptr=&A;

Object pointer are useful in creating object at


runtime.
Objects pointer can access public member of an
object.
A==*ptr
&A==ptr

ptr=&b;
We can use two operator to call public member
function.
dot operator(.) eg. b.print();
(*ptr).print();
or
arrow operator(->) eg. ptr->print();
#include<iostream.h>
#include<conio.h> class derive:public base
class base {
{ public:
public: void display()
void display() {
{ cout<<"\n Derive class display:";
cout<<"\n Base class }
display:" ; void show()
} {
virtual void show() cout<<"\n Derive class show:";
{ }
cout<<"\n Base class };
show:";
}

};
void main()
{ • Output:
clrscr();
base obj1;
base *p; P points to Base
cout<<"\n\t P points to base:\n" ;

p=&obj1; Base class display


p->display();
p->show();
Base class show

cout<<"\n\n\t P points to derive:\n";


derive obj2;
P points to Derive
p=&obj2;
p->display();
Base class Display
p->show();
getch(); Derive class Show
}
Rules for virtual functions

• The virtual function must be members of some class.


• They cannot be static members.
• They are accessed by using object pointer.
• A virtual function can be friend of another class.
• A virtual function in base class must ne defined even though it may
not be used.
• The prototype of base class version of virtual function and all
derived class version must ne identical.
• We cannot have virtual constructor, but can have virtual
destructor.
• A base pointer can point to any type of derived object, reverse is
not true.
• Virtual function are defined in base class, they need not be
redefined in derived class.
Type conversions
• Complier applies rules of automatic type
conversion for constants and different type of
variable.
Ex: int m;
Float x=3.14;
m=x;
• Data on right gets automatically converted into
data type of left variable.
• Type conversion works automatically for built in
data type.
• C3=c1+c2; // all are same class type objects
• Operations is easy to carry out.
• But performing addition on different class object, compiler
gives error.
• Compiler does not support automatic type conversion for user
defined data type.
• We need to design such function ,if required.
• Three type of situation may arise:
1) Conversion from built in type to class type.
2) Class to built in type
3) One class to another class type.
Basic to class type
• A constructor can be used for this type of conversion.
• Ex:
String::String (char *a)
{
int len=strlen(a);
p=new char[len+1];
strcpy(p,a);
}
char name[]=“abcd”;
String s1;
S1=name; //s1=string(name)
Program of converting int type to class type “time”
class time
{
int hrs;
int mins;
public:
time() {}
time(int t)
{
hrs=t/60;
mins=t%60;
}
void display(){ cout<<“hours=“<<hrs<<“mins=“<<mins; }
};
void main()
{
time T1;
int dur=85;
T1=dur; //T1=time(dur); int to class type
T1.display();
Class to basic type
• Here overloaded casting operator(function) is
used to convert class type to basic type.
• Also called conversion function.
syntax:
operator typename()
{ //function statement
}
1) Must be member of class
2) Must not specify a return value
3) Must not have any argument.(no argum for unary
op as member)
Convert a vector to scalar magnitude.
Where magnitude is square root of sum of square of its
components

class vector
void main()
{
int v[20]={1,2,3,4,5,2,3,20}; {
public:
vector(){}
vector v1;
operator double() double len;
{ double sum=0;
for(int i=0;i<8;i++)
len=v1;
{ Or
sum=sum+v[i]*v[i];
}
len=(double)v1;
return sqrt(sum); }
}
One class to another class type
• Obj X = Obj Y;
Destination object source object

• Conversion can be carried out by constructor


or conversion function. Or both
• Any one can be called depending on
destination class.
#include<string.h>
#include<stdlib.h>
class date
{ char dt[10];
public:
date() { dt[0]=‘\0’; }
date(char *s){ strcpy(dt,s); }
void display()
{ cout <<dt; }
};
class dmy
void display()
{
{
int day,mth,yr;
cout<<day<<“\t”<<mth<<“\
public:
t”<<yr;
dmy()
}
{ day=mth=yr=0; }
};
dmy(int d,int m,int y)
{ day=d; mth=m;yr=y; } void main()
operator date() {
{ char str[9],temp[3]; date d1;
itao(day,str,10); dmy d2(17,11,99);
strcat(str,”/”); d1=d2;
itao(mth,temp,10); Or d1=date(d2);
strcat(str,temp); cout<<“d1=“;
strcat(str,”/”); d1.display();
itoa(yr,temp,10); cout<<“\n d2=“;
strcat(str,temp); d2.display();
return (date(str)); }
}
WORKING WITH FILES
12.1 What is a File?
• A file is a collection on information, usually
stored on a computer’s disk. Information can
be saved to files and then later reused.

122
12.2 File Names
• All files are assigned a name that is used for
identification purposes by the operating
system and the user.

123
Table 12-1
File Name and Extension File Contents

M Y PRO G .BA S BASIC program


M EN U .BA T DOS Batch File
IN STA LL.D O C Documentation File
CRU N CH .EX E Executable File
BO B.H TM L HTML (Hypertext Markup Language) File
3D M O D EL.JA V A Java program or applet
IN V EN T.O BJ Object File
PRO G 1.PRJ Borland C++ Project File
A N SI.SY S System Device Driver
REA D M E.TX T Text File
124
The Process of Using a File
• Using a file in a program is a simple three-
step process
– The file must be opened. If the file does not yet
exits, opening it means creating it.
– Information is then saved to the file, read from
the file, or both.
– When the program is finished using the file, the
file must be closed.

125
Figure 12-1

126
Figure 12-2

127
Working with files
Data are read from file and are written in file.
C++ also uses features/files to handles with files
File stream fstream.h
This fstream is used for reading data from files
& writing data to files.
FSTREAM

IFSTREAM OFSTREAM
INPUT STREAM
READ DATA

DATA
INPUT

DISK FILES PROGRAM

DATA
OUTPUT STREAM OUPUT
WRITE DATA
12.4 Setting Up a Program for File
Input/Output
• Before file I/O can be performed, a C++
program must be set up properly.

• File access requires the inclusion of fstream.h

131
• Opening a file
filestreamclass streamObject;
streamObject.open(“filename”);

example:
ifstream i1;
i1.open(“demo.txt”);

ofstream o1;
o1.open(“demo.txt”);
• General syntax:
streamObject.open(“filename”,mode);
Ex: fstream i1;
i1.open(‘abc.txt”,ios::in);

• This is compulsory when fstream is used.

• But if ifstream is used , ios::in is by default


• And if ofstream is used, ios::out is by default
used as a mode:
File Modes
Name Description
ios::in Open file to read
ios::out Open file to write
ios::app All the data you write, is put at the end of the file.
It calls ios::out
ios::ate All the data you write, is put at the end of the file.
It does not call ios::out
ios::trunc Deletes all previous content in the file. (empties
the file)
ios::nocreate If the file does not exist, opening it with the open()
function gets impossible.
ios::noreplace If the file exists, trying to open it with the open()
function, returns an error.
ios::binary Opens the file in binary mode.
12.5 Opening a File
• Before data can be written to or read from a
file, the file must be opened.
ifstream inputFile;
inputFile.open(“customer.dat”);

135
// This program demonstrates the declaration of an
fstream object and the opening of a file.
#include <iostream.h>
#include <fstream.h>

void main()
{
fstream d; // Declare file stream object
char fName[81];
cout << "Enter the name of a file you wish to open or
create: ";
cin.getline(fName, 81);
d.open(fName, ios::out);
cout << "The file " << fName << " was opened.\n";
}

136
Program Output with Example Input

Enter the name of a file you wish to open


or create: mystuff.dat [Enter]
The file mystuff.dat was opened.

137
// This program uses the << operator to write information to a file.
#include <iostream.h>
#include <fstream.h>
void main(void)
{
fstream d;
char line[81];

d.open("demofile.txt", ios::out);
if (!d)
{
cout << "File open error!" << endl;
return;
}
cout << "File opened successfully.\n";
cout << "Now writing information to the file.\n";
d << "Jones\n";
d << "Smith\n";
d << "Willis\n";
d << "Davis\n";
d.close();
cout << "Done.\n";
}
output
Jones
Smith
Willis
Davis
Opening a File at Declaration
fstream dataFile(“names.dat”, ios::in | ios::out);

140
Closing a file
• Function close() is used to close a file.
• It is called automatically by destructor
function.
• It can be called explicitly.
Ex:
ifile.close();
Detecting end of file.
• Detection of end of file condition is necessary
for preventing the compiler to further read
and write to file.
• eof() is used to check whether a file pointer
has reached the end of file.
• If successful, eof() return a non zero,
otherwise return 0;
Ex:
ifstream inf;
inf.open(“filea.txt”);
while(! inf.eof())
{
..
}
File pointers
• Each file has two associated pointers known as the file pointers.

1) input pointer or get pointer.


The get pointer specifies a location from which the
current reading operation is initiated

2)output pointer or put pointer.


The put pointer specifies a location from where the
current writing operation is initiated
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
#include <iostream.h>
#include<conio.h> pointer p is at 0
After welcome
#include <fstream.h> pointer p is at 7
Again
pointer p is at 14
void main() pointer p is at 21
{
clrscr();
fstream fout;
fout.open("hello.txt",ios::app);
int p=fout.tellp();
//fout<<“welcome”;
cout<<"\n pointer p is at "<<p;

getch();
}
File pointers
infile.seekg(10);

Moves the file pointer to the byte number 10.

The bytes in a file are numbered beginning from zero. Thus, the
pointer will be pointing to the 11th byte in the file.
Specifying the offset :
• The seek functions seekg() and seekp() can also be used with
two arguments as follows:

• seekg(offset, refposition);
• seekp(offset, refposition);

• The refposition takes one of the following these constant


defined in the ios class.
• ios::beg start of the file
• ios::cur current position of the pointer
• ios::end end of the file.
File Open Mode
#include <fstream>
int main(void)
{
fstream 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
File I/O Example: Writing
#include <fstream>
using namespace std;
int main(void)
{
ofstream outFile(“fout.txt");
outFile << "Hello World!";
outFile.close();
return 0;
}
Program in c++ to read a string and store it in file.

#include<iostream.h>
#include<conio.h>
#include<fstream.h>
#include<string.h>
void main()
{
clrscr();
char str[80];
cout<<"enter a string";
cin>>str;
int len=strlen(str);
fstream file;
file.open("filea.txt",ios::in | ios::out);
for(int i=0;i<len;i++)
{
file.put(str[i]); //put character to file
file.seekg(0); //goto to start
char ch;
while(file)
{
ch=file.get();
cout<<ch;
}
}

getch();
}
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
Binary File I/O Examples
//Example 1: Using get() and put()
#include <iostream.h>
#include <fstream.h>
void main()
{
fstream File("test_file.bin",ios::out | ios::in | ios::binary);
char ch;
ch='o';
File.put(ch); //put the content of ch to the file
File.seekg(ios::beg); //go to the beginning of the file
ch=File.get(); //read one character
cout << ch << endl; //display it
File.close();
}
Reading /Writing from/to Binary Files
• To write n bytes:
• write ((char *)& n, sizeof(n));
• To read n bytes (to a pre-allocated buffer):
• read ((char *)&num, sizeof(num))
#include <fstream.h>
main()
{
int array[] = {10,23,3,7,9,11,253};
ofstream OutBinaryFile("my_b_file.bin“, ios::out |
ios::binary);
OutBinaryFile.write((char*) array, sizeof(array));
OutBinaryFile.close();
}

You might also like