CHP 3 C++
CHP 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’
#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
} 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.
• Public:
public members can be accessed from outside the
class.
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.
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);
}
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:
}
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.
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.
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;
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" ;
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
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
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
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.
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);
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
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.
getch();
}
File pointers
infile.seekg(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);
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();
}