You are on page 1of 145

C C++

#include <stdio.h> #include <iostream.h>


Function <printf cout. in are objects
Scanf cout << “Hello”;
Insertion operator
Or
Insertors
cout << “value =” <<a;
No need of format specefiers
In C++

Scanf ( “%d”, &a); cin >>a;


Extraction operator
Or
Extractor
cin >>a >>b;
Cascading of extractor;

for next line


Printf ( “Hello \n user”); cout << “Hello \n User”;
Or
cout << “Hello” <<end<<”User”;

In C, default return type in C++ default return


is “void” type is an “integer”

HISTORY OF C++

Year  1982
Developed  Bjarne stroustrap
Lab  Bell Labs
Company  At & T

C is procedure oriented language C is object oriented language

Easy & fast programming in C++ closely models sear world


C. Logics can be easily developed problems Developed.
CLASSES AND OBJECTS

In structure of C :- only data can be member of structure and not functions


All member of structure of are public by default
In class of C++ data + functions accessing those data are member of class and All
member of class are private by default

class stud
{
int roll;
char grade;
float par;
public:
void get( );
void show( );
};
void stud : : get( )
{
cout << “enter roll. Grade and per”;
cin>>roll>> grade >> per;
}
void stud : : show
{
cout <<roll << “ “<< grade << “ “ <<per<< end1;
}

void main( ) roll


{ get
stud s;
s. get ( ); s show grade
s. show( );
}
Per

Function are never seplicated there is only one copy of function no matter now
many objects are created only once memory is allocated to functions for all objects
where as multiple copies of data are created for multiple objects.
: : Scope resolution operator helps compiler to identify functions of which class if
two classes have the same name.

Q. 1 wap to add two numbers give by user


class add
{
int a, b, c;
public :
void get( );
void sum( );
void show( );
};
void add : : get ( )
{
cout << “Enter no”;
cin >> a >>b;
}
void add : : sum( )
{
c= a+b;
}
void add : : show( )
{
cout << “Numbers are = “<< a << “ “ << b;
cout << “sum =” <<c;
}
void main( )
{
add obj;
obj. get( );
obj.sum( );
obj. show( );
getch( );
}
C++ (Terminology) OOPs (Terminology)
1. objects instances
2. data members properties & attributes
3. member function methods & behaviors
4. function call message passing

BASIC PRINCIPLES OF OOP

ENCAPSULATION
Word has been derived from a word capsule which means multiple
medicines packed in one single unit. Similarly in a software there are two major
unit data & functions acting on that data since functions and data are related
entities it is advisable to score them within a single unit. Thus according to oop’s
Encapsulation means building or wrapping up of data members and f n acting on
those data members with in a single unit. Since a class allows us to hold data &
functions within it are say that it supports the principle of encapsulation.

POLYMORPHISM
The word polymorphism is derived from combination of two words
poly mcarning multiple and morph means the ability to have multiple forms. In
other words if an entity can acquire multiple forms in different situation we say
that its behaviors is polymorphic for eg in c++ it is possible for programmer to
redife operator ‘+’ in such a way that it can be used to add two integers as well as
at the same time it can add two abject or two strings. So it a programmer define +
to behave in above mentioned member we say that + behaves polymorphically .
In C++, polymorphism is implemented in two way:-

(1). Compile time polymorphism :- function overloading and operator


Overloading
(ii). RunTime polymorphism:- Virtual functions, pure virtual functions
Abstract classes
(iii). Inheritance :- to inherit means to acquire properties and fea of an
Existing entity into a newly created entity Like a
child acquire properties of his or has Parent, similary when designing
software if a programmer wishes then he can acquire the fratures (data and
member function) of an existing class in his own class with the help of
inheritance. The class which gets inherited is known as bass class and the
class. Thus by inheriting the members of base class it becomes possible to
access them through the objects of derive class. The major advantage offered
by principle of Inheritance is “rcusability and reliability”
CREATING PARAMETERIZED FUNCTIONS WITHIN CLASSES

class Emp
{
int age;
char name[20];
float salary;
public:
void set (int, char *, float);
void show( )
};
void Emp: : set (int I, char *j, float K)
{
age =I;
strcpy(name, j);
salary =k;
}
void Emp : : show( )
{
cout <<age << “ “ <<name << “ “ salary;
}

ASSIGNMENT
Wap to create a class c/a string. The class must contain a character
array of size 20. class should have following fucnitons:

(1). Getstring( ) which accept string as parameter + stores it in array str.


(2). Show string( ) which display the string stored in str[].
(3). Reversestring ( ) which reverses the string stored in str[].
(4). Add string( ) which accepts string as parameter and if possible
Concatenates in str.

Write an object oriented program to calculate the factorial of a given by user.


Provide separated function for initialization, inputting, calculating and display.

class Fact
{
long int f;
int n;
public:
void init( );
void getno( );
void calculate( );
void display( );
};
void Fact : : init( )
{
f=1;
}
void Fact : : getno( )
{
cout << “Enter a number”;
cin >> n;
}
void Fact : : calculate( )
{
int i;
for (i=1; i<=n; i++)
f=f * i;
}
void Fact : : display( )
{
cout << “ Number =” << n;
cout << “factorial=” <<f;
}
void main( )
{
Fact obj ;
obj. init( );
obj.getno( );
obj.get calculate( );
obj. display( );
}

CONTRUCTOR
Constructor :- constructor are special member f n of a class with the following
properties

1. They have the same name as that of the class


2. They don’t have any return type not even void
3. They are automatically called as soon as the object of class is created i.e. their
calling is implicit.
4. They can’t be declared as static
5. They can’t be declared as virtual

Any class which does not contain any constructor then compiler from itself
supplier a constructor but it is hidden. for programmer these constructors are
default

class fact
{

}
Constructors are automatically called even when not declared, at that time
default constructors are called. Default contractors are destroyed as soon as we
declare constructor

Example :-
class fact
{
int n;
long int f;
public:
fact( )
{
f=1;
}
void getno( );
void calculate( );
void display( );
};
void fact : : getno( )
{
cout << “enter a no”;
an >> n;
}
void fact : : calculate( )
{
int i;
for (i=1; i<=n; i++)
f= f * i;
}
void fact : : display ( )
{
cout << “no=” <<n<<end1;
cout << “factorial=” <<f;
}
void main( )
{
fact obj;
obj.getno( );
obj.calculate( );
obj.display( );
}

PARAMETERIZED CONSTRUCTOR

class Emp
{
int age;
char name[20];
float sal;
public:
Emp (int, char *, float);
void show( );
};
Emp : : Emp (int i, char *j, float k)
{
age =i;
strcpy (name, j);
sal=k;
}
void Emp : : show( )
{
cout << age << “ “ << name<< ‘ ‘ <<sal;
}

void main( )
{
Emp e(101,”Amit”,6000.00) ;
e.show( );
getch( );
}

FUNCTION OVERLOADING
void show (int, int, int)
1. No of Arguments void show (int)
2. Type of Argument void show (double)
3. Order of argument void show (int, double)
void show (double, int)

int show ( )
Not allowed (return type differs)
void show( )

Compiler does not consider return type, other wise constructor can never be
overloaded as they have no returns type. Function overloading allows some
function name in same scope but there should be some different in functions.

void vol (int);


void vol (int, int, int );
void main ( )
{
int choice;
cout << “select a figure”;
cout << “ (1) cube \n (2) cuboid”;
cin >> choice;
Switch (choice)
{
case 1:
int s;
cout << “enter side of cube”;
cin >> s;
vol (s);
break;
case 2:
int l, b, h;
cout << “Enter l, b and h of values ”;
cin >> l >> b >> h;
vol (l,b, h);
break;
default:
cout << “wrong choice”;
}
void vol (int s)
{
cout << “value of cube =” << s*s*s;
}
void vol (int l, int b, int h)
{
cout << “value of cuboard=” << l*b*h;
}

ADVANTAGES OF FUNCTION OVERLODING

1. Overload of remembering the name is transformed from programmer to


compiler
2. it develops symmetry & incrrases the readability of program

CONSTRUCTURE OVERLOADING

class Box
{
int l, b,h;
public:
Box( ); //constructor for user defined Box
Box (int); //constructor for
Box(int,int,int);
void show( );
};
Box : : Box( )
{
cout << “enter l, b and h of box”;
cin >> l >> b>> h;
}
Box : : Box(int s)
{
l=b=h=s;
}
Box : : Box (int i, int j, int k)
{
l=i;
b=j;
h=k;
}
void Box : : show( )
{
cout << l << “ “ <<b<< “ “ << h;
}
void main ( )
{
Box B1;
Box B2 (5,7,11);
Box B3 (10);
B1. show( );
B2. show ( );
B3. show ( );
}

COPY CONSTRUCTOR

It is a special constructor of a class which accepts the reference of the object of its
our class as a parameter. It is called by c++ compiler in there situations

1. when ever programmer created an object and at the same time passes another
object of the same class as a parameter
2. whenever a f n accepts an object as a parameter by value.
3. whenever a f n returns an object by value.

Reference variable:-

Syntax:- <data type> & <sef-name> = <var-name>;

void main( ) backs of pointer


{ 1. occupy 2 bytes of memory
int a = 10; 2. will be initialized by garbage
int *p; 3. necessary to initialize before their use
p=&a;
cout <<*p <<end1; 4. very careful in using indirection operator
}

void main ( ) Advantage of Reference variable


{
int a=10; 1. we can have n reference variables of one
int &p=a; variable
cout <<a<< “ “ <<p;
cout << &a << “ “ <<&p; 2. both variables get interlocked on each
Other
3. does not require any memory space it
Only reuse the memory of any variable

Reference variable is a technology provided by c++ which allow a programmer to


create a new variable which stores (not holds) the memory location of an existing
variable. In other words, reference variable is a technique using which programmer
can allot multiple mames to same memory location.

POINTER TO REMEMBER
1. int &p = a;
2. int &p =b;
multiple declarations for the variable p.
3. In case of array, always use pointer. Reference variable can not work with
array
4. we can not make array of reference variable

int &p [4]’


C C C++

pass by value pass by reference pass by reference


void swap (int, int); void swap (int*, int*); void swap (int&,int&);
void main( ) void main( ) void main( )
{ { {
int a,b; int a,b; int a,b;
cout << “Enter2 number”; cout << “Enter2no”; clrscr( ) ;
cin >>a>>b; cin >> a >> b;
swap (a,b); swap (&a, &b) cout << “enter2no”)
cout << a << “ “ <<b; cout <<a<< “ “<<b; cin>>a>>b;
} } swap (a,b);
void swap(int p,intq) void swap (int*p, int*q) cout <<a<< “ “<<b;
{ {
int temp; int temp; }
temp =p; temp=*p; void swap(int&p,int&q)
p=q; *p=*q; {
q=temp; *q= temp; int temp;
} } temp=p;
p=q;
q=temp;
}

Note :- By call it is not possible to call whether it is call by value or call by


reference

Q. WAP to use a function call maximum which accepts an integer array of size
pure as an argument & retirns the largest & smallest element of that array to main.
Without changing the arcginal position of element of ht array.

void Maximum (int a[], int &, int&)


void main( )
{
int a[5], i, large, small;
for (i=0; i<5; i++)
{
cout << “enter elements of array”;
cin >>a[i];
}
Maximum (a, large, small);
cout << “maximum element=” <<large;
cout << “smallert element=” <<small;
}
void Maximum (int a[5], int &max, int & min)
{
max = a[0];
min=a[0];
for(int i=1; i<5; i++)
{
if (*(a+i) >max)
max=* (a+i);
else if (* (a+i) <min)
min = *(a+i);
}
}

class Box
{
int l, b, h;
public:
Box( );
Box (int);
Box (int, int, int);
Box (Box &);
void show( );
};
Box : : Box( )
{
cout << “enter l, b and h of Box”;
cin >> l >> b >> h;
}
Box : : Box (int S)
{
l=b=h=s;
}
Box : : Box (Box &p)
{
l=p.l;
b=p.b;
h=p.h;
}
Box : : Box (int i, int j, int k)
{
l=i;
b=j;
h=k;
}
void Box : : show( )
{
cout << l << “ “ << b << “ “ << h;
}
void main ( )
{
Box B1;
Box B2 (10);
Box B2 (5,7,11);
Box B4 (B1);
B1. show( );
B2.show( );
B3.show( );
B4.show( );
}

Box B2 (10) Box B2 = 10;


Box B4 (B1) Box B4 = B;
Call for copy constructor

Box B4;
B4 = B1
No call for copy constructor use of assignment operator other
destination object is already made.

DEFUALT ARGUMENTS

void printline (char =’*’, int=1);


void main ( )
{
printline ( ); // printline (‘*’, 1)
printline (‘#’); // printline ( ‘#’, 1)
printline (‘!’, 10) // printline (‘!’, 10);
}
void printline (char ch, int n)
{
for (int i=1 i<=n; i++)
cout <<ch;
}

Note;- Default arguments must always be trailing arguments.

printline(50);  printline (ASCII of 50, 1);


class Stud
{
int age;
char grade;
float per;
public:
Stud (int, char, float); // stud (int=o, char= ‘ ; float=0.0);
void get( );
void show( );
};
Stud : : Stud (int I, char j, float k)
{
age =I;
grade= j;
per =k;
}
void Stud : : get( )
{
cout << “Enter age, grade & per ‘;
cin >> age >> grade >> per;
}
void Stud : : show( )
{
cout<< “ age = “<<age<<” \n grade= “<<grade<<” \n per = “<<per;
}
void main( )
{
Stud t ( 15, ‘A’, 75);
Stud p;
p. get( );
t. show( );
p. show( );
}

Note:- In class at same time it is not possible to have default argument constructor
and default constructor.

DESTRUCTOR

Are special member f n of class which have same name as that of the class but
preceded with the symbol of field ( ). They are automatically called whenever an
object goes out of scope & is about to be destroyed

When an object is created first function which is automatically called is


constructor & when object ends its life a last function is called to free occupied
memory is destructor

class Emp
{
int age;
char name [20];
float sal;
public:
Emp( );
~Emp( );
void show( );
};
Emp : : Emp( )
{
cout << “Enter age, name & sal”;
cin >> age >> name >> sal;
}
void Emp : : show( ) Note
{ A class by default has 3 built in
cout <<age << “name <<sal; fucntion
} 1. Constructor
Emp : :~ Emp( ) 2. copy constructor
{ 3. Destructor
cout << “Object destroyed”;
} Note:- Destructor are always called in
void main( ) reverse order.
{
Emp e, f,;
e. show( );
f. show( );
}

Create a class c/o student having 3 data members (i) for storing Roll no. (ii) for
storing name (iii) for storing marks in subjects

The member for storing name should be char *, member for storing marks should
be int *;

Create constructor of class which prompts user to enter length of name,


allocates sufficient memory & accepts the name from user. The same constructor
asks the user how many subject he want to enter, againallocate sufficient memory
for that & accepts the marks given by user. Finally provide appropriate member f n
which display % & grade of student. At the end define the destructor in proper
manner to deallocate memory allocated by constructor.

class student
{
int roll ,n;
char * name, grade;
int *marks;
float per;
public:
student ( );
void get();
void calculate( );
void show( );
~student( );
}

student : : student ( )
{
cout << “how many letters”;
cin >>n;
name = (char *) malloc ((n+1) * sizeof (char));
if (name= = NULL)
exit(1);
get( );
}
void student : : get( )
{
cout << “ enter roll no”;
cin >> roll ;
cout << “enter name”;
cin >> name;
cout << “how many subject are there enter ”;
cin >>n;
marks=(int*)malloc(n*2);
for (i=0; i<n; i++)
{
cout << “Enter marks”;
cin >> * (marks+i);
}
}

void student : : calculate ( )


{
per=0;
for (int i=0; i<n; i++)
per+= * (marks+i)
per =per/n;
if (per >=75)
grade = ‘A’;
else if (per >=60)
grade = ‘B’;
else
grade = ‘f’;
}
student : :~ student ( )
{
free (name);
free(marks);
}
void student : : show( )
{
cout<<” Name = “<<name<<”\n roll number = “<<roll;
cout<<” per=”<<per<<” \n grade=”<<grade;
for(int i=0;i<n;i++)
cout<<”\n “<<marks[i];
}
void main( )
{
sudent s;
s. calculate( );
s. show( );
}
Note In C++, cin don’t accepts the space
void main( )
{
char str[20];
cout << “enter name”;
cin >> str;
}
cin.getline (str, 80); //Enter Key /9.

Prototype of get line ( )


void get line (char *, int );
Member of istream header file

COMPARISION BETWEEN
CONSTRUCTOR & DESTRUCTOR

CONSTRUCTOR
1. are special member f n of a class having same name as that of the class.
2. constructors are automatically called as soon as object of class is created i.e.
their calling is implicit
3. constructors can be parameterized.
4. since constructors accepts parameters they can be overloaded & thus a class
can have multiple constructors.
5. constructors are called in the orders in which objects are created.
6. constructors can not be inherited.
7. constructors can not be declared as virtual.
DESTRUCTOR

1. are special member fn of class having same name as that of the class but
preceded with the symbol of tilde
2. a destructor is also automatically called but whenever an object is about to be
destructor or goes out of scope thus these calling is implicit.
3. we can not pass parameters to a destructor.
4. as they don’t accept parameters we can not overload then, thus a class can not
have multiple destructor
5. calling of destructor is always done in reverse or des of the creation of objects.
6. inheriting of destructor is also not possible
7. we can have virtual destructor in a class.

INLINE FUCNTIONS

Inline functions
Are those fn whose call is replaced by their body during
compilation. Declaring a fn as inline has two major advantages.

1. compiler does not has to leave the calling fn as it finds definition of fn being
called their it self.
2. The overhead of maintaing the stack in belureen function call is seduced
Thus declaring a function as inline increases the execution
Speed, s\reuces execution time & thus enhances the overall efficiency of program.
But two ptr must be considered before declaring a fn as inline

1. The definition of inline function must appear before its call i.e. if a non
member fn is to be made inline then its declaration & definition must appear
about main as a single unit.
2. the body of inline fn must be short & small
3. it should not contain any complex keywords or keyword or statement like for,
if, while, dowhile do,
if any of the aboul sules are violated then compiler ignores the
keyword inline an treats the fn as offline or normal one. Moreover a
class can have two kinds of inline functions

1.Implicit Inline :- fn efined within the body of class


2. Explicit Inline :- fn declared within the class but defined outside the class
preceded with the keyword inline.

Thus at the end we can say, that declaring a fn as line is a request


made by programmer which the later may agrel or deny.

class Emp
{
char name [20];
int age;
float sal;
public :
void get( )
Implicit {
Inline cout << “enter age, name and sal”;
cin >> age >> name >> sal;
}
void show( );
};

Explicit inline void Emp : : show( )


Inline {
cout << age << “ “<<name << “ “<<sal;
}

void main( )
{
Emp E[5];
int i
for (i=0; i<5; i++)
E[i]. get( );
for (i=0; i<5; i++)
E[i] show( );
}

STORAGE CLASSES

Storage class decides the following

1. Default value
2. life (persistence)
3. scope (accessibility)

storage default life scope


1.auto garbage limited to limited to declaration block
(automatic) their
Declaration
Block
2. static Zero throughout “
The program
3. register garbage same as auto same as auto
4. global zero throughout throughout the program
The program

Auto Static
void display ( ); void display ( );
void main( ) void main ( )
{ {
display( ); display( );
display ( ); display ( );
display ( ); display( );
} }
void display( ) void display( )
{ {
int a;
cout <<a<<end1; static int a;
a++; cout <<a<<end1;
} a++;
}
o/p 3 garbage values will be o/p  0
generated 1
2

STATIC DATA
Static data members with in the class
class data
{
int a ;
Static int b;
}; 0 b

a a
int data : : b;
d1 D2

static variable don’t wait for creation of object, before object creation memory is
allocated for then
of class
1. A static data member has a single copy shared amongst each object of that
class. On other hand if a class has non static data then every object of that
class has its own copy of non static data
2. static data members arrive in memory even before objects of the class get
created. Because of their feature it becomes necessary to redefine them outside
the class so that they can be given space in RAM without the help of object.
3. since they are not related to any particular object of the class & have a single
copy in the entire class, a static data member never contributes in the size of
object. In other words size of object is always calculated by summing up sizes
of non static members.
WAP to create a class c/o student having two data members roll & count. The
member roll should keep the roll no. allocated to every student object while the
members count should keep track of total no. of student objects currently in the
memory. Finally provide appropriate members fn to initialize & display the values
of Roll no. & count.

class Student
{
int roll;
static int count;
public:
Student (int i)
{
roll=i;
++ count ;
}
void show( )
{
cout << “Roll no=” <<roll<<end1;
cout << “total objects alive =” <<count;
}
~Student ( )
{
--count;
}
};
int student : : count;
void main( )
{
Student S=10;
Student P=20;
Student Q=30;
S. show( );
P. show( );
Q. show( );
{
Student X = 40;
Student Y=50;
X. show( );
Y. show( );
}
}

STATIC FUCNITON

Syntax
<class-name> : : <function-name>(list of arguments);

RESTRICTIONS ON STATIC FUNCTIONS

1. static f n can never access non –static data numbers. But reverse is true.
2. Constructor & Destructor can never be made or declared as static.
3. If a static function is defined outside the class the keyword static cannot be
used.

class student
{
int roll;
static int count;
public :
student (int i)
{
roll =i;
++count;
}
void show( )
{
cout<<roll;

}
static void total_student()
{
cout << “total objects alive =” <<count;
}
~student ( )
{
--count;
}
};
int student : : count;
void main( )
{
student S(10). P(20), Q(30);
S.show();
P.show();
Q.show();
student : : total_student( );
{
student X(40), Y(50);
X. show( );
Y.show();
student::total_student();
}
student::total_student();

}
student::total_student();
getch( );
}

Program :- Create a class c/a employa having data members for storing age, name
& id. Also provide another member which stores the next id which will be
allocated to next incoming object. Provide a member f n to initialize this variable
with its initial value & also provide appropriate constructor & member f n for
initialized all other members of class.

class Emp
{
int age;
char name [20];
int id;
static int nid;
public:
static void init( )
{
id=nid;
}
Emp( )
{
cout << “enter age, name”;
cin >> age >> name;
id=nid;
++nid;
}
void show( )
{
cout <<age<<name<<id;
}
};

Solution :-

class Employee
{
int age;
char name[20];
int id;
Static int nextid;
public:
Employee (int, char *);
static void initid( );
void show( );
static void getnextid( );
~Employee( );
};

int Employee :: nextid;


Employee : : Employee (int I, char * j)
{
age =I;
strcpy (name,j);
id = nextid++;
}
void Employee : : initid( )
{
nextid=1;
}
void Employee :: show( )
{
cout <<age<< “ “<name << “ “<< id<<end1;
}
void Employce : : getnextid( )
{
cout << “next employee will be given id=” <<nextid;
}
Employce : : ~Employee( )
{
--nextid;
}
void main( )
{
Employee : : initid( );
Employee : : getnextid( );
{
Employee e (25, “Rahul”);
Employee f (30, “vipin”);
e. show( );
f. show( );
Employee : : getnextid( );
}
Employee : : getnextid( );
}

“this” POINTER

class Emp
{
int age;
char name[20];
float sal;
public :
void get( )
{
cout << “enter age, name & sal”:
cin >> age>> name>>sal;
cout << “Address of calling object =” <<this;
}
void show( )
{
cout <<age<<name<<sal;
cout << “Address of calling object=” <<this;
}
};
void main( )
{
Emp E, F;
E.get( );
F.get( );
E.show( );
F.show( );’
}

1. Every member f n of class has this pointer.


2. No need to declare & initialize this pointer. Compiler initialize it with base
address of calling object.

“this” POINTER

This is a special pointer available in every member foundation of a class except


static member f n of a class. Whenever the object of a class puts a call to any non
static member f n of that class, the this pointer available in that member f n
implicitly starts pointing to the address of calling object. Thus we can say that a
“this” pointer always points or referr to the aurrent object.

By default class has 3 “this” pointer.


Constructor copy constructor Destructor

Accessing Data Member Using ‘this”

class Box
{
int l, b, h;
public:
Box( );
Box (int, int, int );
Box (Box &);
void show( );
};
Box : : Box( )
{
cout << “Enter l, b, and h”;
cin >> l >> b >> h;
}
Box : : Box (int I, int j, int k)
{
l=i; /* can also be written as thisl=l;
b=j; thisb=b;
h=k; thish=h;*/

Box : : Box (Box &p)


{
l=p.l;
b=p.b;
h=p.h
/* can also be written as *this=p;*/

}
void Box : : show( )
{
cout << l << “ “ <<b<< “ “ <<h;
cout << this  l << thisb << this h;
}
void main( )
{
Box B1;
Box B2 (5, 7, 11);
Box B3 = B1;
B1. show( );
B2. show( );
B3. show( );
}

LIMITATIONS OF THIS

This pointer always points to calling object thus it can not be


incremented or decremented. It is a constant pointer.

Box = *q;
Q = this+1 // valid
Q=++this // not valid

USING THE “const” KEYWORD

1. Const variable
2. pointer to const C
3. const pointer
4. const pointer to const variable
5. const parameters
6. “ data members of class
7. “ member f n of a class

“const” Variables
void main ( )
{
const float pi=3.14;
}
Const variable are initialized at the pt of declaration menns they are read
only variables & their values can not be manipulated.

cout <<pi++ ; // not valid.

“const” Pointer
const int *p;// read as “p is a pointer to a const int”
void main( )
{
int b=50;
int a =10;
const int *p; // can also be written as “int const *p”
p= &a;
*p=20;// invalid operation
p=&b;// valid operation
}

int * const P :- is a const pointer to an integer means P can’t be incremented or


decremented. Thus they are initialized at the time of declaration.
(“this” pointer comes in the above category.)

void main( )
{
int b=50;
int a=10;
int * const p=&a;
*p=20;
p=&b

“const” parameter:
When the const modifier is used with a pointer parameter in a function's
parameter list, the function cannot modify the variable that the pointer
points to.
For example,

int strlen(const char *p)

Here the strlen function is prevented from modifying the string that p points to.

Working on the same theme the prototype of a copy constructor is actually

<classname>(<classname> &<referencename>)

For example:
Box (const Box &p) // prototype of default copy constructor
{
L=p.l;
B=p.b
H=p.h
}
Const data members of class
Many times we have some data members in a class whose values should remain
unaltered after they are initialized. To create such members we can use the “const”
keyword in front of their declaration and such members are called “const”
members. But they must be initialized using initializers.
For example

class circle
{
int rad;
const float pi; // This is invalid
};

Rather the class should have a constructor to initialize “pi” using initializers.

class circle
{
int rad;
const float pi; // This is invalid
public:
circle (int r) : pie (3.14)
{
rad=r;
}
};

Const Member Function:-

if we want that a f n that should not be allowed tochange value of class


member than we make them const.

class circle
{
int r;
float a;
public:
void get (int x)
{
r=x;
}
void cal_area ( )
{
a=r * r * 3.14;
}
void show ( ) const
{
count << “Rad=” <<r << “\t Area=” <<a;
}
if const is there then value of r will not be changed other wise at last it
will be incremented.

INITIALIZERS

Inializers
It is a special syntax allotted by C++ used to initialize there thing .

1. const data members with in the class.


2. reference variables
3. calling parameterized constructor of the base class from derived class.

They are always written in front of the constructors


Orders of initializes must be same as that of the order of data members

class Data
{
int x, y;
public:
Data (int I, int j): x(i), y(j)
{

}
Data (int I, int j): x(i+j), y(x+i)
{
}
};

Ist case
Data D(5,10)
X=5
Y=10
Data D(7,14)
X=21
Y=28

PASSING OBEJCTS USING POINTER

class Box
{
int l, b, h;
public:
void get( )
{
// same as previous
}
int compare (Box *);
};
int Box : : compare (Box *p)
{
int x, y;
x= l*b*h;
y=P l* pb* ph;
if (x= = y)
return (0);
if (x>y)
return (1);
else
return (-1);
}
void main( )
{
Box B1, B2;
B1. get( );
B2. get( );
B1. show( );
B2. show( );
int ans ;
ans = B1. compare (&B2);
if (ans= =0)
cout<<” both are equal “;
else if (ans==1)
cout<<”b1 is greater than b2”;
else
cout<<”b2 is greatyer than b1”;
}

Passing Objects by Reference Using Reference Variable

class Box
{
int l, b, h;
public:
void get( )
{
// same as previous;
}
void show( )
{
// same as previous;
}
int compare (Box &);
};
int Box : : compare (const Box &P)
{
int x, y;
x = l*b*h;
y = p.l*p.b*p.h;
if (x==y)
return (0);
else if (x > y)
return (1);
else
return (-1);
}

void main( )
{
Box B1, B2;
B1.get( );
B2.get( );
B1.show( );
B2.show( );
int ans;
ans=B1. compare (B2);
if (ans= =0)
cout<<” both are equal “;
else if (ans==1)
cout<<”b1 is greater than b2”;
else
cout<<”b2 is greatyer than b1”;
}

FRIEND FUNCTIONS

A friend function is a special function which despite of not being


member f n of class has full access to the private, protected members of the
class.

ATTRIBUTES OF FRIEND FUNCTIONS

1. if a Function is to be made friend of a class then it has to be declared within


the body of the class preceded with the keyword friend.
2. whenever a friend f n is defined neither, the name of class nor scope
resolution operator appears in its definition. Moreour the keyword friend
also does not appear.
3. whenever a friend fn is called, neither the name of the object nor dot
operator appears toward its left. It may however accept – the object as a
4.
5.
6. parameter whose members it wants to access.
7. It does not matter in which diction of class we declare a friend function as
we can always access it from any portion of program
8. if a friend fn want to manipulate the values of data members of an object it
veds the reference of object to be passed as parameter

Example:- // Demonstrating the use of friend function


class student
{
int roll;
char grade;
float per;
public:
void get( );
friend void show (student);
};
void student : : get( )
{
cout << “enter roll. Grade & per”;
cin >> roll>> grade>>per;
}
void show (student P)
{
cout << p.roll<< “ “ << p.grade<< “ “ <<P.per;
}
void main( )
{
student S;
S. get( );
show(S);
}

Demonstrating the use of friend function

class student
{
int roll;
char grade;
float per;
public:
friend void get (student &);
void show( );
};
void get (student & P)
{
cout << enter roll, grade & per”;
cin >> P.roll >> P.grade >> P.per;
}
void student : : show( )
{
cout << roll << grade << per;
}
void main( )
{
Student S;
void get(S);
s. show( );
}

class student
{
int roll;
char grade;
float per;
public:
friend void get (student *P);
void show( );
};
void get (student *q)
{
cout << “enter roll, grade & per”;
cin >>q  roll >> q grade >> q per;
}
void student : : show ( )
{
cout << roll << grade << per;
}
void main( )
{
Student s;
Get (&s);
s.show( );
}

A FUNCTION BEING FRIEND OF TWO CLASSES


class Beta; // forward declaration
class Alpha
{
int x;
public:
void get( )
{
cout << “enter x=”;
cin >> x;
}
friend void compare (Alpha, Beta);
};
class Beta
{
int y;
public:
void set( )
{
cout << “enter y=”;
cin >>y;
}
friend void compare (Alpha, Beta);
}
void compare (Alpha A, Beta B)
{
if (A, X > B. Y)
cout << “greater=” << A, X;
else if (B.Y> A.X)
cout << “Greater=” << B.Y;
else
cout << “equal”;
}
void main( )
{
Alpha Obj1;
Beta Obj2;
Obj1. get( );
Obj2. set( );
Compare (obj1, obj2);
}
ADDING TWO OBJECTS OF A CLASS USING MEMEBR FUCNTIONS

class Distance
{
int feet;
int in cher;
public:
void get( )
{
cout << “enter feet & inches”;
cin >> feet >> inches;
}
Distance add (Distance &)
void show( )
{
cout << “feet=” << feet<< “inches=” <<inches;
}
};
Distance Distance : : add (Distance &P)
{
Distance temp;
Temp. feet = feet +P. feet;
Temp.inches= inches + P.inches;
if (temp. inches>=12)
{
temp. feer += temp. inches/12;
temp. inches % =12
}
Return (temp);
}
void main( )
{
Distance D1, D2, D3;
D1. get( );
D2, get( );
D3 = D1. add (d2);
D3. show( );
}
class Distance
{
int feet, inches;
public:
void get( 0
{
// same as previous
}
void add (distance &, distance &);
void show( )
{
// same as previous;
}
};
void distance : : add (distance &d1, distance &d2)
{
Feet = d1. feet + d2, feet;
Inches = d1. inches + d2, inches
if (inches >12)
{
Feet = feet + inches /12;
Inches % = 12;
}
}
void main( )
{
Distance d1, d2, d3; d1.get( );, d2.get( );
D3, add (d1, d2);
D3. show( );
}

ADDING TWO AF CLASS UISNG PRIED FUNCTION

class distance
{
int feet;
int inches;
public:
void get( )
{
void << “enter feet & inches”;
cin >>feet >> inches;
}
void show( )
{
//same
}
friend distance add (distance, distance ):
};
distance add (distance P, distance Q)
{
distance temp;
temp. feet = P.feet +Q.feet;
temp. inches= P.inches + Q.inches;
if (temp. inches>=12)
{
temp.feet += temp. inches/12;
temp. inches % = 12;
}
return (temp);
}
void main( )
{
distance D1, D2, D3;
D1.get( );
D2.get( );
D3 = add (D1, D2)
D3.show( );
}

OPERATOR OVERLOADING

It is a mechanism using which a programmer can make built in


operator of C++ act on objects of user defined classes much in the same way like
they act on variables of primitive data type. Thus we can say by using operator
overloading a programmer can enhance the working range of built in operator from
primitive type to non primitive type also.

The major advantage offered by operator overloading is the simplicity


in readability of the call i.e. f n call which are given using operator overloading are
much more easy to interpret as compared to conventional function calls.

Operator Overloading can be done

1. Making use of member function


2. making use of friend function.

Syntax:-
<ret-type> operator <op-symbol> (arguments);
friend (ret-type> operator <op-symbol> (<arguments>);

Overloading Of Unary Operator As Member Function Of The class


(Pre Increment)

class counter
{
int count;
public:
counter( )
{
count =0;
}
counter (int c)
{
count = c
}
void operator ++( );
void show( )
{
cout << count <<end1;
}
};
void counter : : operator ++ ( )
{
++ count;
}
void main( )
{
counter a = 10; // Single parameterize constractor
a.show( );
++ a; // a. operator + +( );
a. show( );
}

class Counter
{
int count;
public:
Counter( )
{
Count = 0;
}
Counter (int c)
{
count = c;
}
Counter operator ++ ( );
void show( )
{
cout << count;
}
};
Counter &
Or
Counter Counter : : operator ++ ( )
{
Counter temp;
++ count; or
temp. count = count; ++ count
return (temp); return (* this);
}
void main( )
{
Counter c1 = 10, c2;
C1. show( );
C2 = ++ c1;
C1. show( );
C2. show ( );
}

Overloading Of Post Increment Operator Using Member Function Of this class

class Counter
{
int count;
public:
Counter( )
{
count=0;
}
Counter(int C)
{
count = c;
}
Counter operator ++ (int);
void show( )
{
cout << count;
}
};
Counter Counter : : operator ++ (int)
{
Counter temp;
Temp. count = count++;
return (temp);
}
void main( )
{
Counter c1 = 10, c2;
C2 = c1++;
C1. show( );
C2. show( );
}

Overloading Unary Operator As friend Of The class


class counter
{
int count;
public:
counter( 0
{
count=0;
}
counter (int i)
{
count = I;
}
void show( )
{
cout << count << end1;
}
friend void operator ++ (counter &);
};

void operator ++ (counter &C)


{ Or
++ c.count counter temp;
return (C); temp. count = c.count++;
} return (temp);

void main ( )
{
counter C1 = 10, C2;
C1. show ( );
C2. = ++C2;
C1. show ( );
C2. show( );
}

Note:- when unary operators are overloading using member function then
don’t accept any argument but when they are overloaded using friend fn then they
have one argument of type object (class).

class counter
{
int count;
public:
friend counter operator ++ (counter &);
counter
{
count =0;
}
counter (int i)
{
count = i;
{
void show( )
{
cout << count << end1;
}
};

counter operator ++(counter &c)


{
counter temp;
temp.count=++c.ount;
return(temp);
}

void main()
{
counter c1=10,c2;
c1.show();
c2=++c1;
c1.show();
c2.show();
getch();
}

Overloading Binary Operators As Member Functions Of The class


D3 = D1 + D2;
D3 = D1. operator + (D2);

class Distance
{
int feet, inches;
public:
void get( )
{
Count << “enter feet and inches”;
cin >> feet >> inches;
}
void show( )
{
cout << feet << inches;
}
Distance operator + (Distance);
};
Distance Disttacne : : operator + (Distance P)
{
Distance t;
t.feet = feet + P. feet
t. inches = inches + P. inches;
if (t.inches>= /12)
{
t.feet + = t.inches/12;
t.inches % = 12;
}
Return (t);
}
void main ( )
{
Distance D1, D2, D3;
D1, get( );
D2, get( );
D3 = D1+D2;
D3. show( );
Getch( );
}
Overloading Binary Operator Using friend Function

class Distance
{
int feet, inches;
public:
void get( )
{
cout << “enter feet and inches”:
cin >> feet>> inches;
}
void show( )
{
cout << feet<< inches;
}
friend Distance operator + (Distance, Distance);
};
Distance Operator + (Distance p, Distance Q)
{
Distance t;
t.feet = P.feet +Q.feet;
t.inches = P.inches+ Q.inches;
if (t. feet>=12)
{
t.feet = t.feet +t.inches/12;
t.inches % = 12;
}
Return (t);
}
void main ( )
{
Distance D1, D2, D3;
D1.get( );
D2.get( );
D3=D1+d2;
D3.show( );
}

Assignment:-
D2 = D1+n
D3 = n + D1

class Distance
{
int feet, inches;
public:
void get( )
{
// same as previous
}
void show( )
{
// same as previous
}
Distance Distance : : operator + (int n)
{
Distance temp;
Temp feet = feet + n;
Temp. inches = inches + n;
if (temp. inches > = 12)
{
Temp. feet + = temp. inches / 12;
Temp. inches % = 12;
}
Return (temp);
}
Distance operator + (int P, Distance Q)
{
Distance temp;
Temp.feet = P+Q.feet;
Temp. inches= P+Q. inches;
if (temp. inches> = 12)
{
Temp.feet = temp. feet + temp. inches/12;
Temp. inches % = 12;
}
Return (temp);
}
void main( )
{
Distance D1, D2, D3;
int n;
cout << “enter an integer”;
cin >> n;
D1. get ( );

I D2 = D1+n; // can be done using member fn & friend fn


D2. show( );
cout << “Enter an integer”;
cin >>n;
II D3 = n+D1; // not possible through member fn
D3. show( );
}

Note:-
II can not be done using member function becoz n is an integer and only an
object can call function not integer. So I call can be made using member function
as well as friend function but II can be done only friend function

Assignment :- D1+=D2  using member fn & friend fn

Overloading Relational Operators

if (D1= = D2)
Compiler if (D1.operator = = (D2) )

class Distance
{
int feet, inches;
public:
void get( )
{
cout << enter feet & inches”;
cin >> feet >> inches;
}
void show( )
{
cout << feet << “ “ << inches;
}
int operator = = (distance D);
};
int Distance : : operator = = (Distance D)
{
int x, y;
X= feet &12 + inches;
Y = D. feet *12 + D.inches;
if (x= = y)
Return (1);
else
Return (0);
}
void main( 0
{
Distance D1, D2;
D1. get( );
D2. get( );
D1. show( );
D2.show( );
if (D1= = D2)
cout << “equal”;
else
cout << “not equal”;
}

Assignment:-
Modify the above program so that now your cosle prents either of
there message
i. Object are equal.
ii. Dl is greater.
iii. D2 is greater
Use minimum possible operator

Overloading Binary Operator On string

class string
{
char str[20];
public:
string ( )
{
str[0] = ‘\0’;
}
string (char *P);
{
strcpy (str, P);
}
void show( )
{
cout << str;
}
string operator + (string S)
};
string string : : operator + (string S)
{
string t;
int i, j;
for (i=0; str[i]; i++)
t.str[i] = str[i];
for (j=0; s.str[j]; i++, j++)
t.str[i] = s.str[j];
return (t);
}
void main( )
{
string s1= “Hello”;
string s2 = “How are you ?”;
string s3;
s3 = s1 +s2;
s1. show( );
s2. show( );
s3. show( );
}

Assignment :-
WAP which compares two string objects & checks which one is
greater.

Operators Which Can Not Be Overloaded


1> .(dot operator)  member access operator (already overloaded)
2> :: (scope resolution operator) it already works on classes we overload
only those operators which works on primitine and not on non prin
3> ?: (conditional Operator) It requires there arguments overloading of
operators atmost can take 2 argument
4> *.  Pointer to member operator
5> Size of operator

DYNAMIC MEMORY ALLOCATION (DMA)

MALLOC NEW
1. It is a function It is a operator
2. Necessary to include the header file header file not required
3. It takes no, of bytes as parameter It takes no. of elements
Required as parameter
4. brings memory from local heap bring has no such memory store
5. Maximum memory that malloc New has no such memory
B
can allocate = 64K limitation
6. Malloc retirens the address of New automatically converts
Allocate block in from of (void*) according to the datatype given
Thus its return value has to be type thus no need to explicitly type
Casted accordingly cast its return value.
7. when malloc fails it returns null when new fails it returns zero
8. Malloc only creates a new block on the other hand operator new
But not call the constructor of the can allocate memory as well as
class for initialized the data member call the class for initializing the
Of that block members of block created. Such
Constructors are called dynamic
Constructors.

Syntax for new;-

(i) new <data – type>


(ii) new <data-type> [int];

Allocations Of New :-
1. int * P; new allows programmer to initialize the memory
P= new int (10); allocated but malloc does not provide nay such feature
cout << *P;
delete P;

2000 10

P 2000 2002

2. int *P; Here value 10 denotes that


P=new int [10]; programmer is interested in creating memory for
delete [ ] P; elements

3000 ..

P 3000

Syntax for delete

1. delete <ptr-name>; // deletes one block of data type


2. delete [ ] <ptr-name>; // deletes whole allocated memory

Eg:- float *P;


delete P; // four bytes free

Delete is a request to OS it does not work immediately where as new creates


memory immediately

WAP which creates a dynamic array of user defined size Accept values from user
in that array & then find largest element in that array along with its position.
Finally it should display the largest element & delete the array.

void main ( )
{
int n;
cout << “How many integers”;
cin >> n;
int *p;
p= new int [n];
if (p= = 0)
{
cout << “Insufficient memory”;
getch( );
exit(1);
}
for (int i=0; i<n; i++)
{
cout << “enter element”;
cin >> * (p+i);
}
int max = *p;
int pos = 0;
for (i=1; i<n; i++)
{
if (*(p+i) > max)
{
max = *(p+i);
pos = i;
}
}
cout << “largest element=” << max;
cout << “Position =” << pos;
getch( );
delete [ ] p;
}

WAP to create a class c/a string having a character pointer P. provide constructor
in the class which accept int as parameter and allocates dynamic array of characters
of special size. Now provide following member fn in the class.

1. get string  which prompts users to enter string in dynamic array.


2. show string  which display the string
3. Reverse string  which accept an object as parameter and copies the
Reverse of string stored in calling object in object
Passed as parameter.
class string
{
char *p;
int n;
public :
string (int);
string ( );
void showstr( );
void reversestr ( string &);
void getstr( );
};
string : : string (int size)
{
p = new char [size +1];
if (p= =0)
exit (1);
n = size +1;
}

void string : : getstr( )


{
cout << “enter string”;
cin. getline (p,n);
}
void string : : reversestr (string &s)
{
int i, j;
for (i=0, j=strlen (p)-1;j>=0; j--, i++)
{
s.p[i] = p[j];
}
s. p[i] = ‘\0’;
}

void string : : showstr( )


{
cout << p << end1;
}
string : : string ( )
{
delete [ ]p;
cout << “ Array destroyed”;
}
void main ( )
{
int n;
cout << “How may character”;
cin >> n
string S1 =n;
string S2 =n;
S1. getstr ( );
S1. reverse str(S2);
S1. show str( );
S2. show str( );
}

DYNAMIC OBJECTS

Allocating memory for class with the help of new.

class Emp
{
int age;
char name[20];
float sal;
public:
void get( )
{
cout << “enter age, name & sal”;
cin >> age >> name >> sal;
}
void show( )
{
cout << age << “ “ << name<< “ “ <<sal;
}
};
void main( )
{
Emp *P;
P=new Emp();
if (P= =0)
{
cout << “Memory Insufficient”;
exit (1);
}

P get( );
P show( );
getch ( );
delete p;
}

P age name sal

ARRAY OF DYNAMIC OBJECTS

Modify the previous code so that now your program creates an array of a objects
where n is given by user. Then it should accept values for each object and finally
display them.

class Emp
{
int age;
char name[20];
float sal;
void get( )
{
cout << “enter are, name and sal”;
cin >> age>> name>> sal;
}
void show( )
{
cout <<age<< name<<sal<<end1;
}
};
void main( )
{
Emp *p;
int i, n;
cout << “how many employees?”;
cin >> n;
p=new Emp[n];
if ( p = =0)
{
cout << “error in crating objects”;
exit (1);
}
for (i=0; i<n; i++)
(p+i)  get( ); or p[i]. get( );
for (i=0; i<n; i++)
(p+i)  show( ); or p[i]. show( );
getch( );
delete[ ]p;
}

Enhance the above program so that after accepting records of n employees. Your
program prompts the user to enter another name & display the record of that
employee only. if employee name is not available then program should display the
message record not found.

class Emp
{
int age;
char name [20];
float sal;
public:
void get( )
{
cout << “enter age, name and sal”;
cin >> age>> name>> sal;
}
void show( )
{
cout << age<< name << sal;
}
int compare (char *);
};
void main ( )
{
Emp *p;
int n;
cout << “how many employees?”;
cin >> n;
P= new emp [n];
if (p = =0)
{
cout << “Insufficient Memory”;
exit (1);
}

for (i=0; i<n; i++0


(p+i)  get( ); or p[i]. get( );
cout << “enter name to search”;
char str [20];
cin. ignore( );
cin.getline (str, 20);
for (i=0; i<n; i++)
{
if ( (p+i) compare (str) = = 0)
{
(p+i)  show ( );
break;
}
}
if (i = = n)
cout << “ Record not found”;
getch ( );
delete [ ] p;
}
int compare (char *p)
{
return (strcmp ( name.p) );
}
DYNAMIC COSNTRUCTORS

class Emp
{
int age;
char age;
char name [20];
float sal;
public;
Emp( )
{
cout << “enter age, name and sal;
cin >> age >> name >> sal;
}
Emp (int I, char *j , float k)
{
Age = I;
Strcpy (name, j);
Sal = k;
}
void show( )
{
cout << age << “ “ name “ “ << sal;
}
~Emp( )
{
cout << “Object destroyed”;
}
};
void main ( )
{
Emp *P, *q;
P=new Emp;
Q=new Emp (30, “vineet”, 200000);
p show( );
q show( );
delete q;
delete p;
}
Note:- The above Program will not call the destructor of the class even at the
termination. This is because in C++ memory which is allocated using new can only
be deal located using delete and calling of destructor is only made when memory
gets deallocated. Since in above code, call for delete is not present so memory
block still remains in RAM & might be collected in future through garbage
collection. Thus if memory is freed for a dynamic object it can only be done
through delete operator.

INHERITANCE

1. Single Inheritance 2. Multi level Inheritance

A Base class A indirect base class of C

B Derived class B base class of C

3. Multiple Inheritance 4. Hierarchial Inheritance

A B A

C B C

5. Hybrid Inheritance or Multipath Inheritance

A
B C

Syntax for Inheritance:-

class <class –name>: public / private / protected < clas-name>

Derived class Mode of Inheritance Base class

class Box
{
int l, b, h;
public:
void get( )
{
cout << “enter l, band”;
cin >> l>>b>>h;
}
void show( )
{
cout <<l<< “ “ << b<< “ “ << h;
}
};
class carton : public Box
{
char type[20];
public:
void set( )
{
cout << “enter material name”;
cin.getline (type, 20);
}
void display ( )
{
cout << “material =” << type;
}
};
void main( )
{
carton obj;
obj. get( );
obj. set( );
obj. show( );
obj. display( );
}

Accessability Rules When Mode Of Inheritance Is public

When a base class is inheritance in public mode then :-

1. All the public members of base class become public members of derived
class i.e. they can be accessed through the function of derived class as well
as by objects of derived class.
2. All the protected members of base class become protected members of
derive class & thus can only be accessed through functions of derived class
but not by the object (main) of derived class.
3. All private members of base remain private to their own class & thus can
neither be accessed through functions of derive class nor by object of derive
class.

EARLY BINDING:-
It is a prours which is executed during compilation in which
compiler binary the fn body with the fn call i.e. even before program starts
executing decision regarding the fn call and fn body to be executed are taken by the
compiler since this happens before execution, we can say it is early binding. Early
binding is always an action until & unless keyword virtual is used infront of the fn
return type. It is done on the basis of there criterias:-

(i) function name or


(ii) calling object type or
(iii) function parameter type

in other words early binding is always in action in normal fn calls,


overloaded fn calls and overloaded operators
The major benefit of early binding is speed of execution i.e. function
calls which are bound using early binding get executed at a fastest speed as
compared to late binding fn calls.

OVERRIING
The function overriding is a term which is used when a derive class
contains a function with the same prototype as its bass class. In other words, fn
provided by base class has same prototype in derive class but in different body.

Overriding Overloading
Scope must be different always in same class
By the classes related by means at single level
Inheritance

Prototype of functions prototype must be different


Must be same .

When Mode Of Inheritance Is Protected

When base class is inheritance in protected mode then:-

1. All public members of base class becomes protected member of derive class
i.e. they can be accessed only through function of derived class but not by
object of derive class.
2. All protected members of base class become protected members of derive
class i.e. they two can only be accessed through functions of derived class
but not by object of derive class.
3. All private members of base class remains private to their own class & thus
neither accessible through the object nor through functions of derive class.

class Num
{
protected:
int a, b;
public:
void get( )
{
cout << “enter two numbers”;
cin >> a >> b;
}
void show( )
{
cout << “Numbers are =”;
cout <<a << “ “ << b;
}
};

class AddNum : protected Num


{
Protected :
int c;
public:
void set( )
{
get( );
}
void add( )
{
c=a+b;
}
void display( )
{
show( );
cout << “sum=” <<c;
}
};
void main ( )
{
AddNum obj;
obj. set( );
obj.add( );
obj. display( );
}

PRIVATE MODE OF INHERITANCE

When a base class is inheritance in private mode then:-


1. All the public members of base class become private members of derive
class i.e. they can be only accessed through fn of derive class but not by the
objects of derive class.
2. All the protected members of base become private members of derive class
i.e. they two can only be accessed through the function of derive class but
not by objects of derive class.
3. All private members of base class remain private to their own class & thus
can neither be accessed by fn nor by objects of derives class.

class Num
{
protected :
int a, b;
public:
void get( )
{
cout << “enter a and b”;
cin >> a >> b;
}
void show( )
{
cout << “a = “<<a<<end1;
cout << “b= “<< b<< end1;
}
};

class AddNum: private Num


{
protected :
int c;
public:
void set( )
{
get( );
}
void add( )
{
c=a+b;
}
void display ( )
{
show( );
cout << “sum = “<<c;
}
};
void main( )
{
AddNum Obj;
Obj.set( );
Obj. add( );
Obj. display( );
}

Note:- At single level Inheritance private & protected inheritance seems to be


similar.

MULTILEVEL INHERITANCE

class Num
{
protected:
int a, b;
public:
void get( )
{
cout << “enter a nad b”:
cin >> a >> b;
}
void show( )
{
cout << “a=” <<a<<end1;
cout << “b=” <<b<<end1;
}
};
class AddNum : public Num
{
protected :
int c;
public :
void set( )
{
get( );
}
void display( )
{
show( );
cout << “sum=” <<c;
}
void add( )
{
c=a+b;
}
};

class DiffNum : public AddNum


{
int d;
public:
void accept( )
{
set( );
}
void diff( )
{
d= a – b;
}
void print( )
{
display ( );
cout << “Difference=” <<d;
}
};
void main( )
{
DiffNum obj;
obj. accept( );
obj. add( );
obj. diff( );
obj. print( );
}
Program

class counter
{
protected:
int count;
public:
void init (int a)
{
count =a;
}
void operator ++( )
{
count ++;
}
void show( )
{
cout << “count=” <<count;
}
};
class DecCounter : public counter
{
public:
void operator - -( )
{
- - count;
}
};
void main( )
{
Deccounter D;
D.int(10);
D.show( );
++D;
D.show( );
- - D;
D. show( );
}
Assignment :-
Create a class c/a array which contains an integer array of size 10. The
class should have two member functions called get arr and showarr, which should
accept values in the array & display its values respectively. Now create a derive
class of array c/a sortarr, the class should accept a string as parameter if string
contains ‘asc’ then sorting should be done in ascending order & if it contains
“desc” sorting should be done in descending order.

Finally create the function main which should contain menu drive
interface for the user having 5 options:-

(i) input
(ii) display
(iii) sort in ascending
(iv) sort in descending
(v) quit

Solution  #include <iostream.h>


#include <stdlib.h>
class Array
{
protected:
int a[5];
public:
void get( );
void display( );
};
void Array : : get( )
{
int i;
cout << “enter array elements”;
for (i=0; i<5; i++)
cin >>a[i];
}
void Array : : display ( )
{
for (int i=0; i<5; i++)
cout << “\n elements are =” << a[i];
}
class sortarr : public Array
{
public:
void ascsort( );
void descsort( );
};
void sortarr : : ascsort ( )
{
int i, j, t;
for (i=0; i<5; i++)
{
for (j=0; j<4; j++)
{
if (a [j] > a [j+1])
{
t = a [j];
a [j] = a [j+1];
a [j+1] = t;
}
}
}
}
void sortarr : : descsort( )
{
int i, j, t;
for (i=0; i<5; i++)
{
for (j=0; j<4; j++)
{
if (a[j] <a [j+1])
{
t=a[j];
a[j]=a[j+1]
a[j+1] = t;
}
}
}
}

void main( )
{
clrscr( );
sortarr sr;
int ch=0;
do
{
cout << “\n \t Enter (1) for Input data”;
cout << “\n \t Enter (2) for Display Data”;
cout << “\n \t Enter (3) sort in Ascending order”;
cout << “\n \t Enter (4) sort in Descending order”;
cout << “\n \t Enter (5) for quit”;
cout << “enter choice”;
cin >> ch;
clrscr( );
switch (ch)
{
case 1:
sr.get( );
break;
case 2:
sr.display( );
break;
case 3:
sr.ascsort( );
break;
case 4: sr.descsort( );
break;
case 5:
exit(1)
}
} while (ch !=5)
getch( );
}

MULTIPLE INHERITANCE

class base1
{
protected:
int a;
public:
void get( )
{
cout << “enter a =”;
cin >>a;
}
void show( )
{
cout <<a << end1;
}
};
class base2
{
protected:
int b;
public:
void set( )
{
cout << “enter b=”;
cin >> b;
}
void display( )
{
cout <<b << end1;
}
};

class drv : public base1, public base2


{
int c;
public :
void accept ( )
{
get( );
set( );
}
void add ( )
{
c = a+b;
}
void print( )
{
show( );
display( );
cout << “sem =” <<c;
}
};
void main( )
{
drv obj;
obj. accept( );
obj. add( );
obj. print( );
}

Program :-
Base & derive having the function with same name & arguments.

class base1
{
protected:
int a;
public:
void get( )
{
cout << “enter a=”;
cin >>a;
}
void show( )
{
cout << a << end1;
}
};
class base2
{
protected:
int b;
public:
void set( )
{
cout << “enter b=”;
cin >> b;
}
void show( )
{
cout <<b<<end1;
}
};

class drv : public base1, public base2


{
int c;
public:
void accept( )
{
get( );
set( );
}
void add( )
{
c= a+b;
}
void print( )
{
Will show show( ); base1: : show( );
Error ambiguity base2: : show( );
error
}
};
void main( )
{
Drv obj;
obj. accept( );
obj. add( );
obj. print( );
}

Role Of Constructor & Destructor In Inheritance


As a basic rule in inheritance, it a base class contains a constructor and
destructor as well as derive class also contains constructor & destructor, then when
object of derive class is created, constructor of base class gets executed first
followed by constructor of derive class and the destructor is called in reverse order
i.e. the destructor of derive class is called first followed by the destructor of base
class.

Thus we can say constructor are always called in the order of inheritance and
destructor are called in reverse order.

class Base
{
public :
Base ( )
{
cout << In base’s constructor” <<end1;
}
~Base( )
{
cout << In base’s destructor “<<end1;
}
};

class drv: public Base


{
public:
drv( )
{
cout << “In derive’s const “<<end1;
}
~drv( )
{
cout << “In derives destructor “<<end1:
}
};
void main( )
{
{
drv obj;
}
getch( );
}

PARAMETERIES CONSTRUCTOR

class Base
{
Protected:
int a, b;
public:
Base (int I, int j)
{
a = I;
b = j;
}
void show( )
{
cout << a << “ “ << b;
}
};
class drv : public base
{
int c;
public:
drv ( ): Base (10, 20)
{
c=a+b;
}
void show( )
{
Base : : show( );
cout << “sum = “ << c;
}
};
void main( )
{
drv obj1
drv obj2
obj1. show( );
obj2. show( );
}

Constructor Calling In Multiple Inheritance

Base 1 base2 drv

int a; int b; int c;


Base1 (int); base2 (int);
void show( ); void display();

class Base1
{
protected:
int a;
public:
Base (int i)
{
a = i;
}
void show( )
{
cout << a;
}
};
class Base2
{
protected :
int b;
public:
Base2 (int j)
{
b = j;
}
void display( )
{
cout << b;
}
};

class drv: public Base1, public Base2


{
protected :
int c;
public:
drv (int p, int q) : Base1 (p), Base2(q)
{
c=a+b;
}
void print ( )
{
show ( );
display( );
cout << “their sum =” << c;
}
};
void main( )
{
drv obj1 (10, 20);
drv obj2 (20, 70);
obj1. print ( );
obj2. print( );
}

Note :-
if the constructor of base class is parameterized then

(i) derive class must have constructor


(ii) Base class constructor should be called in derives constructor.

Constructor Calling In Multilevel Inheritance

class Base1
{
protected:
int a ;
public:
Base1(int i)
{
a=i;
}
void show( )
{
cout << a << end1;
}
};
class Base2: public Base1
{
protected:
int b;
public:
Base2 (int i, int j): Base1(i)
{
b=j;
}
void display( )
{
cout << b << end1;
}
};
class drv : public Base1, public Base2
{
protected:
int c;
public:
drv (int x, int y) : base2 (x, y)
{
c=a+b;
}
void print ( )
{
show( );
display ( );
cout << “their sum=” << c;
}
};
void main ( )
{
drv obj(10, 20);
drv obj (50, 60);
obj1. print( );
obj2. print( );
}

Note
Constructors can not be inherited :-

Constructors are special member fn which are exclusively used for


initialing private data members of class. Now since the private data of class is not
passed on to its derive classes, so the functions which explicitly initialize then
(constructor) are not inherited. Same is the case with destructor,

HIERARCHIAL INHERITANCE

class Num
{
protected :
int a, b:
public :
Num (int i, int j)
{
a = i;
b = j;
}
void show( )
{
cout << “a =” << a;
cout << “b=” << b;
}
};
class AddNum : public Num
{
int c;
public:
AddNum (int i, int j) : Num (i, j)
{
c=a+b;
{
void show( )
{
Num : : show( );
cout << “ sum =” <<c;
}
};

class Diffnum : public Num


{
int d;
public :
DiffNum (int x, int y) : Num (x, y)
{
d= a – b;
}
void show( )
{
Num : : show( );
cout << “ Difference =” << d;
}
};
void main( )
{
AddNum addobj (10, 20);
DiffNUm diffobj (30, 70);
addobj. show( );
diffobj. Show( );
}

HYBRID INHERITANCE

class Base
{
public:
int a;
};
class drv1 : virtual public Base
{
public:
int b;
};
class drv2: virtual pubic Base
{
public:
int c;
};
class drv3 : public drv1, public drv2
{
public:
int d;
};
void main( )
{
drv3 obj;
obj. a =10;
obj. b = 20
obj. c =30;
obj.d= obj a + obj.b + obj. c;
cout << “sum =” << obj,d;
}

GRATING ACCESS

class Data
{
private :
int a;
Protected :
int b;
public :
int c;
};
class drv : protected Data
{
public:
Data : : C // bring C in public mode instead of protected
};
Foreg:-
class Bank
{
public :
void deposit( );
void withdraw( );
void int-cal( );
};
class saving – acct: Private Bank
{
public :
Bank : : deposit;
Bank : : with draw;
};

POLYMORPHISM

class Base
{
public:
void show( )
{
cout << “In base ‘& show”;
}
};
class drv : public Base
{
public :
void show( )
{
cout << “In drv’s show”;
}
};
void main( )
{
Base b, *ptr;
drv d;
ptr = & b;
ptr  show( );
ptr = & d;
ptr  show( );
}

VIRTUAL FUNCTION & MULTILEVEL INHERITANCE

class Base
{
public:
virtual void show( )
{
cout << “In base’s show”;
}
};
class drv1 : public Base
{
public :
void show( )
{
cout << “In drv1’s show”;
}
};
class drv2: public drv1
{
public:
void show( )
{
cout << “In drv2’s show”;
}
};
void main( )
{
Base * ptr, b;
drv1 d1;
drv2 d2;
ptr = & b;
ptr  show( );
ptr = & d1;
ptr  show( );
ptr = &d2;
ptr  show( );
}

Note :-
Top level class ptr can access member of lower level class. Virtual is
mandaroty in base show as function is originally from base.

Virtual functions are those functions for which no decision regarding the call
and the definition to be executed is token by the compiler during compilation. In
other words, if a fn is preceded with keyword virtual then if never become the past
of early binding & compiler delays its binding until runtime. Thus all the decisions
regarding the call and the body to be executed are taken at runtime. These
decisions are not based on the type of caller (as was the case with early binding)
but on the bases of contents of the caller. if the calling pointer is storing the address
of base class object then base’s version of virtual function will be executed & if it
pointing to an object of derive class then derive version of virtual fn is executed.

But to fully uses the potential of virtual function the derive class while
giving its own body /definition for virtual fn must keep its prototype same as the
base class i.e. derive should override the virtual function of base class if it wants to
place its own definition of virtual function.

This is because pointer of base class can access only those function of
derive class which are overridden in the derive class but not those which are
hidden or added by derive class.

Internal Working Of Virtual Function

class A VTABLE FOR A


{
int a; &A : : f2( )
public:
void f1( ) &A : : f3( )
{
}
virtual void f2( ) obj1 VPTR a
{
}
}; VTABLE FOR B
class B : public A &B : : f2( )
{ int x;
public: &A : f3( )
void f4( );
void f2( ); obj2 VPTR
};

void main( )’
{ size of class A = 4 bytes
A obj1;
A *ptr; 2 bytes for variable a
ptr = & obj1; 2 bytes for VPTR
ptr  f2( );
ptr = & obj2;
ptr  f3( );
ptr  f4( );
} This will not be executed since this is not virtual & compiler
will go to Early binding table for base class A where there is no function f4.

VTABLE:-
for every class in C++ which contains at least one virtual function a
special look up table for storing addresses of there virtual function is created which
is known as VTABLE or virtual Table. Thus in short VTABLE is a table
containing addresses of virtual functions of the class as well as virtual function of
base class if they are not overridden. This table is then consulted by the compiler
when a call for virtual function is encountered during runtime.

VVPTR:- (Virtual void Pointer)


for every class which contains a virtual function special pointer is
created by the compiler known as VVPTR, which is used for pointing to the virtual
table. Thus every object of class containing virtual function has its size
incremented by2. Now whenever compiler encounters call for virtual function
through a pointer, it first refers to the address of object to which pointer is pointing
from their it reads the address contained in VVPTR of the object the which is the
address of VTABLE of class. Lastly within the VATBLE it executes the virtual
function called. Thus virtual function enhances the size of code as reduces the
execution speed but provides a flexible way of designing program which can
respond to the changes which accur at run time.

class Data
{
int a ;
Data (int );
public:
static Data getObject( );
void show( );
};
Data : : Data (int i)
{
a = i;
}
Data Data : : getobject( )
{
Data D(10);
return (D);
}
void Data : : show( )
{
cout << a;
}
void main( )
{
Data D = Data. getobject( );
D. show( );
}
Note
When only one object of class is created then that type of class is c/a single
to n class.

Polymorphism
Compile Time Polymorphism Run Time Polymorphism
1. Function Overloading 1. Function Overriding
2. Operator Overloading 2. Virtual Function
3. Early Binding 3. Late Binding

Virtual Inheritance avoids multiple copies

Polymorphism
(converts early binding to late binding)

class Figure
{
protected:
int dim1, dim2;
public :
void get( )
{
cout << “enter 1st & 2nd dimension”;
cin >> dim1>> dim2;
}
};
class Rectangle : public Figure
{
public:
void area( )
{
cout << “area of Rectangle=”;
cout << dim1 * dim2;
}
};

class Triangle : public Figure


{
public:
void area( )
{
cout << “area =” <<’5 * dim1 *dim2;
}
};
void main( )
{
Figure *p;
Figure F;
p = &F;
p get( );
p area( );
Rectangle R;
p=&R;
p get( );
p area( );
Triangle T;
p = & T;
p get( );
p area( );
}

PURE VIRTAUL FUNCTIONS

Def:- if a virtual functions declarations is equated with zero then it is


known as pure virtual fn. In other words, it we do not want to provide any
definition for a virtual fn wee can equate with zero then it will be known as pure
virtual fn. Thus by definition a pure virtual fn is one which has no body define with
in its own class or base class.

ABSTRACT CLASS

1. if a class contain at least one pure virtual fn than it is known as abstract Base
class.
2. we can never create any object of abstract class but we can always create its
pointers. This is because whenever an object of a class containing virtual
function is created a VTABLE is setup by the complete, which stores the
address of virtual function has no body it can not have memory address &
thus it can not places in VTABLE. So to prevent any accidental calls to a
non-existing pure virtual function compiler prohibits the creation of an
object of an abstract class.
3. An class which extends an Abstract Base class must provide its own
definition of pure virtual fn available in its base class other wise the class
itself would be created as an abstract class & then it too can not be
instantiated.

Note:- Constructors can not be virtual since link between VPTR VTABLE
is made by constructor

Virtual Destructor:-

class Base
{
protected:
int *p;
public: base( )
{
p=new int [10];
cout << “ p constructed!”;
}
virtual ~ base
{
delete [ ] p;
cout << “memory deallocated”;
}
};
class drv : public Base
{
int *q;
public :
drv( )
{
q = new int [10];
cout << “ q constructed”;
}
~drv( )
{
delete [ ] q;
cout << “memory deallocated for q”;
}
};
void main( )
{
Base *ptr;
ptr = new drv;
delete ptr;
}

Destructor can not be declared as pure virtual. Since it is not possible to leave
empty body of destructor since at the time of call of destructor same activity must
be performed.

FILE – HANDLING (STREAM I/O)


Flow of data

if flow of data is from program towards device then o/p stream eg. cout . is used.

if flow of data is from device to program then i/p stream eg cin is used.

Monitor / Buffer Monitor

Input stream output stream

C++ Program

Input stream output stream

Hard-disk Hard disk

Classes Available In C++ for File Handling

1. Of Stream:- if a class whose objects can be created for writing data to


secondary memory of file.
2. It Stream:- is a class whose objects can be created for reading data
from file.

3. Fstream :- whose object can read / write the data in a file.

Steap Required for Writing Data In File

Step  1 Create the object of “Of stream” class


Eg:- Of stream obj;
Step 2 Connect the object with file on your system.
Step 3 write the data through the object in file.
Step 4 Close the file.

C++ Implement Of Above Steps

Step 1 (a) Of stream obj;


Step 2 obj. Open ( “Data. Txt”);
Step 3 (a) obj << “Hello”;
(b) obj. put (‘H’);
Step 4 obj.close ( );

1 (a) Of stream Obj ( “Data, txt”);


2(a) Of stream obj; clas static data
Bj.open (“Data. Txt”, ios : : app)
File Opening Mode

3 Of stream obj ( “Data. Txt”, ios : : app)

Step for Creating A Program for Reading A File

1. Create the object of “ifstream” class.


2. Connect the object with the file on your system & check whether file is
available or not.
3. Read the data through object from file.
4. class file.

C++ IMPLEMENTATION
1. if stream obj
2. (a) Obj. Open ( “Data.txt);
Or
if stream obj;
Obj.open ( “Data. Txt”, ios : : in);
Or
if stream obj (“Data.txt”, ios: : in);

Creating Object Of fstream class

1. fstream obj;
Obj.open ( “Data.text”, ios : : out | ios : : in);
2. Using Constructor
Fstream obj ( “Data.txt”, ios : : out | ios : : in);

WAP to create a file c/a “message. text” Accept a line of text from user & write it
in file character by character

#include <stdlib.h>
#include <iostream.h>
#include <fstream.h>
#include <conio.h>

void main ( )
{
Of stream out ( “Message. Text”);
if (!out)
{
cout << “file can not be opened”;
Getch ( );
exit(1);
}
char str[80];
cout << “enter a line of text”;
cin.qetline (str, 80);
int i=0;
While (str[i])
{
Out.put (str[i]);
I++;
}
cout << “file written successfully”;
Getch ( );
Out. Close( );
}

1
Note:- isopen ( ) Returns 1 if conceted
0
1
Fail( ) Retruns I if not connected
0

Que:- WAP to open the file created by the previous program. Read it on character
by character basic & display its contents on the screen.

Solution :-
void main ( )
{
if stream in ( “message.txt”);
if (! in)
{
cout << “filoe can not be opened”;
exit(1);
}
char ch;
While (! In.enf( ) )
{
Ch=in.get( );
cout << ch;
}
Getch( );
In.close( );
}

Que:- WAP to open a file c/a “Data.txt”. Accept a line of text from user & write it
on file character by character basic and it in the same program read file and print
its content on the screen .

void main( )
{
Fstream Nisha ( “Data”, ios: : out | ios: : in);
if (! Nisha)
{
cout << “error opening file”;
exit(1);
}
char str [80];
cout << “enter a line of text”;
cin.get line (str, 80);
int i=0;
char ch;
While (str [i])
{
Ch=str[i];
Obj.put (ch);
I++;
}
Obj.seekg (0);
While (! Obj.eof( ) )
{
Ch=obj.get( );
cout << ch;
}
Getch( );
Obj. close( );
}

Que  Assume there is a file c/a “Message. Txt” containing certain line of txt.
Create a file c/a “Message2.txt, and copy the contents of “messages.txt” into it.
Before coping the character must be converted upper to lower & vice versa &
spaces must be skipper. Finally display the contents of “Message2 txt”.

void main( )
{
if stream obj1 ( “Messages.txt”);
Stream obj2 (“Message2. txt”, ios : : out | ios : : in);
char ch;
if (! Obj1)
{
cout << sourcl file cant be opened”;
exit(1);
}
While (! Obj1, eof)
{
Ch = obj1. get( );
if (ch! = 32)
{
if (ch>=65 & & ch<=90)
Ch=ch+32;
else if (ch > =97 && ch <=122)
Ch=ch-32;
}
Obj2.put(ch);
}
Obj2.seekg(0);
While ( ! obj2. eof( ) )
{
Ch=obj2. get( );
cout << ch;
}
Getch( );
Obj2.closs( );
Obj1. close( );
}

READING AND WRITING STRINGS

void main ( )
{
Fstream obj ( “Data.txt”, ios : : out | ios : : in);
if !(!obj)
{
cout << “error”;
exit (1);
}
char text [80];
cout << “how many lines”;
int n;
cin >> n;
cout << “Enter “ << n<< “lines each terminated by enter : “<<end1;
for (in i=1; i<=n; i++)
{
cin.get line (text, 80);
Obj << text << end1;
}
Obj. seekg (0);
cout << “File written press nay key to read”;
Gecth( 0;
While (!obj.eof( ) )
{
Obj.getline (text,80);
cout << text << end1;
}
Gecth( );
Obj.close( );
}
void main( )
{
Fstream obj ( “Data.txt”, ios : : out | ios : : in);
if (!obj)
{
cout << “error”;
exit(1);
}
char text [80];
cout << “enter lines and press enter on new line to stop”;
While (1)
{
cin.getline (text, 80);
if (strlen (text) = =0)
Break;
Obj << text << end1;
}
}

FILE OPENING MODES

1. ios : : out (Default mode of ofstream)


if file is not existing then it is created. Otherwise data gets
Erased and pointer is placed at the beginning.

2. ios : : in
if file is existing, pointer is placed a the beginning otherwise
error is generated.
3. ios : : app
It can not alter previous contents but can add new content at the
End of file.

4. ios : : ate (ate stands for at the end)


Allows updations as well as adding of new data.
In this pointer can move forward and backward.

5. ios : : trunc
Needed only in fstream.
Used with ios : : out
Truncate previous data & brings pointer to beginning.

6. ios : : nerplace
Used with ios : : out if file is existing do not replace it otherwise
create it.

7. ios : : nocreate
Used with ios : : out if file is existing overwrite it otherwise do not
create it.

8. ios : : binary
if we want to write data in binary form.

BINARY I /O

void write (char *, int )


Of stream address of variable no of bytes to be written
Member whose data is to be
Written

int a = 23091 ;
Obj, write (( char *) &a, size of (int) );
char b = ‘x’;
Obj.seekg(0);
int c;
Obj. read ( (char *) &c, size of (int ) );
cout << c;
char d;
Obj. read (&d, size of (char) );
cout <<d;
int read (char *, int)
Address of variable whose data is to be stored after reading
From file
On successfully reading from file it returns 1 on error it return 0.

Reading and writing class objects

class Emp
{
int age;
char name [20];
float sal;
public:
void get( )
{
cout << “ enter age, name and sal”;
cin >> age >> name>> sal;
}
void show( )
{
cout << age << “ “ <<name << “ “ sal <<end1;
}
};

void main ( )
{
Emp E;
Fstream obj ( “Records.dat”, ios : : out | ios : : in | ios : : trunc| ios : :
Binary );
if (! Obj)
{
cout << “error in opening file”;
exit (1);
}
E.get( );
Obj.write ((char *) &E, size of (Emp) );
Obj.seekg(0);
Emp F;
Obj.read ((char *) &F, size of (Emp));
F.show( );
Getch( );
Obj.close( );
}

Reading And Writing Multiple Objects

void main ( )
{
Emp E;
Fstream obj ( “Record.dat’, ios: : out| ios : : in | ios : : trunc | ios : :
Binary);
if (! Obj)
{
Out << “error in opening file”;
exit (1);
}
char choice;

{
e.get( );
obj.write ((char *) &E, size of (Emp));
cout << “Any More (Y/N)”;
cin.ignore( );
cin >> choice;
} while ( ch = = ‘y’);
Obj. seekg (0);
While (opj.read (char *) &E, size of (emp))
E.show( );
getch( );
obj.close( );
}
Typical Feature Of Read:-

Note :- if in any ane program, we want to read file successively to eof


we must clear the flag
Obj. seekg (0);
Obj. clear( );

Q. WAP to write multiple records of type emp in a file. Accept a name from user
& display the record of the employee by searching it with in the file and display
the appropriate message

void main( )
{
int flat = 0
Emp E;
Fstream obj1 ( “Ekta, txt”, ios : : out | ios : : in | ios : : trunc |
Ios : ; binary);
if (! Obj)
{
cout << “error”;
exit(1);
}
char ch;
Do
{
E.get( );
Obj.write ( ( char *) &E, size of (Emp));
cout << “Ant more (y/n)”;
cin . ignore ( );
} while (ch = = ‘Y’);
char name [20];
cout << “enter name to search”;
cin >> name;
Obj. seekg(0);

While (obj.read (char *) &E, size of (emp))


{
if ( ! ( E = = name) )
{
E. show( );
Flag =1;
Break;
}
}
if ( ! flag) or if (flag = =0)
{
cout << “ Record not found”;
Obj1. close( );
}
int operator = = (char * ptr)
{
Return (strcmp (name, ptr) );
}
}

RANDOM I/O

Q. Assume there is a file c/a “Record.dat” which contains several records of type
emp. WAP to open this file & read the last record.

void main ( )
{
ifstream in ( “Records.dal”, ios : : in | ios : : binary);
if ( ! in)
{
cout << “error”;
exit (1);
}
In.seekg (-1 * size of (emp), ios : : end);
Emp E;
In. read ( ( char *) &E, size of (emp));
E.show( );
In.close( );
Getch( );
}

Note:- Prototype of seekg( )


void seekg (int, int)
No, of position of movement
Bytes to ios : : beg
Move ios : : cur
Ios : : end

WAP to accept a name from user. Search the record of that employee in
“Records.dat” & Add a new record at its position by accepting it from user

void main( )
{
char temp[20];
Emp E;
Fstream in ( “Records.dat”, ios : : in | ios : : ate| ios : : binary);
cout << “enter name to update”;
cin >> temp;
In.seekg(0);
While (in.read ( (char *) &E, size of (emp) )
{
if ( ( E = =temp) = =0)
{
E.get( );
In.seekg (-1 * size of (Emp), ios : : cur);
In.write ( ( char *) &E, size of (emp));
Breack;
}
}
In.clear( );
In.seekg(0);
While (in.read ( ( char *) &E, size of (Emp) )
E.show( );
int operator = =(char *n)
{
Return (strcmp (temp, ptr) );
}
}

Assignment :-

1. WAP to delete record given by user from file.


2. WAP to update just the salary of employee whose name given by user.
TEMPLATES

Templates are a technique provide by C++ using which a programmer


can define a single function in which last to be carried out is mentioned but the
datatype is not mentioned. During runtime by looking at the call of the function &
its parameter type the compiler generates specific version of that function to act
according to parameter passed.

Thus in other words, we can say templates are generic functions


which at the time of creation are only told what to do & during run time they
become aware on what type of argument it has to be done.

Templates are of two type


(i) Function Template
(ii) class Template

Syntax Function Template


Template <class <type-name> > <return – type>
< function-name> (< type-name> <arg-name>)

Example

Template <class T>


void display ( T n)
{
cout << n << end1;
}
void main ( )
{
int a =10;
char b = ‘x’;
float c= 11.5;
Display (a);
Display (b);
Display (c);
}

Write a function template c/a swap which accepts two parameters & swaps then.
Parameters passed can be two integer, two floats two class. Finally two swapped
values must be displayed in the function main

Template <class T>


void swap ( T &a, T &b)
{
T temp;
Temp = a;
A= b;
B = temp;
}
void main ( )
{
int a, b;
cout << “enter two integers”;
cin >> a >> b;
Swap (a, b);
cout << ‘a= “<<a<< “b=” <<b<<end1;
cout << “enter two character”;
char p, q;
cin >> p >>q;
Swap (p, q);
cout << “p= “<<p<<’q = “<<q <<end1;
float x, y;
cout << “enter two float numbers”;
cin >> x>>y;
Swap (x, y);
cout << “x= “<<x<< “y= “<<y << end1;
}

Q. write a function template which accepts two values as an argument & return
maximum amongst then.

Template <class T>


T greater ( T &P, T 7q)
{
if ( p > q)
Return (p);
else
Return (q);
}
void main ( )
{
int a, b;
cout << “enter two integers:”;
cin >> a >> b;
cout << “ maximum = “<< greater (a, b);
cout << “Enter two charr:”
char x, y;
cin >> x >>y;
cout << “maximum =” << greater (x, y);
}

Write a function template c/a greatest which accepts an array as an argument &
returns the largest element of that array. The array passed can be of different type
and different size.

Template <class T>


T greatest ( T *a, int n)
{
int I;
T max = *a;
for (i=1; i<n ; i++)
{
if ( * (a+i) > max)
Max = * (a+i);
}
Return (max);
}
void main ( )
{
int arr[ ] = {7, 11, 2, 3, 4, 8};
float brr[ ] = { 10.4, 11.3, 6.5, 8.2};
cout << “max int =” << max (arr, 6);
cout “max float=” << max (brr, 4);
}
CLASS TEMPLATE

Template <class T>

class Data
{
T a;
T b;
T c;
public:
void get( )
{
cin >> a >> b;
}
void add ( )
{
C = a+b;
}
void show( )
{
cout << “ values are =” << a << end1;
cout << b;
cout << “sum=” <<c;
}
};
void main ( )
{
Data <int> obj1;
Data ,double> bj2;
cout << “enter two int”;
Obj1.add( );
cout << “enter two doubles”;
Obj1, get( );
Obj2. add( );
Obj1. show( );
Obj2. show( );
}
class Template With Different Generic Type

Template <class T1, class T2>


class Data
{
T1, a;
T2, b;
public:
void get( )
{
cin >> a >>b;
}
void show( )
{
cout << “values are =” << a << “and “<< b<< end1;
}
};
void main( )
{
Data <int, float> obj1;
Data <double, char> obj2;
cout << “enter an int and float”;
Obj1.get( );
Obj1.show( );
cout << “enter double and char”;
Obj2.get( )
Obj2.show( );
}

Q. write a class template for a class called stack and implement three basic
operations of stack push, pop and peek. The stack can be of int, char and flots.

Template <class>
class stack
{
T arr [S];
int tos;
public:
Stack ( )
{
Tos = -1;
}
T pop ( );
};
Template <class T>
void stack <T> : : push (T n)
{
if (tos = = 4)
{
cout << “stack overflow”;
Return;
}
++ tos
Arr [tos] = n;
}
Template <class T>
T stack <T> : : pop ( )
{
if (tos = = -1)
{
cout << “stack under floaw”;
Return(-1)
}
Return (arr [tos - -]);
}

void main ( )
{
Stack <int> sa;
int n;
Stack <char> s2;
char ch;
for (int i=1; i<=6; i++)
{
cout << “enter int to be pushed”;
cin >> n;
S1.push(n);
}
for (int i=1; I,6; i++)
cout << “ element popped =” << s1.pop( );
}

Overloading Of Assignment Operator

class string
{
char *p;
public:
string (int);
void set string (char *);
void resetstrign ( char *);
void display ( );
string( );
};
string : : string (int n)
{
P=new int [n+1];
}
void string : : setstring (char *str)
{
Strcpy (p, str);
}
void string : : resetstring (char *s)
{
Strcpy (p, s);
}
void string : : display ( )
{
cout << p <<end1;
}
string : : string( )
{
Delete [ ] p;
cout << “Memory deallocated”;
}
void main ( )
{
string s1 = 20;
string s2 = 20;
S11. setstring ( “Hello User”);
S2=s1;
S1. display ( );
S2. display ( ); void string : : operator (string
S1. resetstring ( “Welcome”); &s)
S1. display ( ); {
S2. display( ); strcpy 9p, s.p);
} x=s.x;
}

Note:-
when ever the class is containing dynamic pointer then it is necessary to
overload assignment operator

At the time of overloading = it is necessary to pass parameter by reference.


( eg ( string & s) ).

Note :-
for cascading of assignment operator it is necessary that return type must be
string

string string : : operator = (string &s)


{
string (p, s, p);
X= s,x;
Return (* this);
}

Note :-
Q. why do we overload assignment operator?

Ans:- The default assignment operator provided by C++ is used for copying one
object of class to another but it copies the value bit by bit i.e. the value contained in
every bit of source object are copied in every bit of destination object. This
behaviour is perfect if source cosle is not containing any pointer to dynamically
alloveated block, but if it is so then the default equl to (=) operator will simply
copy the address stored in the pointer with in source object to pointer in the
destination object. This will make two the defferent pointers point to same location
which may cause multiple problems like the destructor calling delete operator for
the same memory to overcome this, a programmer should overload the equal (=)
operator & provide his own definition for copying the data pointer by pointer of
source object rather than address.

Overloading Of Insertion And Extraction Operator

Prototy Of << operator:-


friend ostream & operator << (ostream & cout, strudent &p);

class Emp
{
int age;
char name [20];
float sal;
public:
friend istream & operator >> (istream 7, Emp&);
friend ostream & operator << (ostream &, Emp &);
};
Istream & operator >> (istream & in, Emp & p)
{
In >> P.age >> P.sal >> P.name;
Return (in);
}
Ostream & operator << (ostream & out, Emp &P)
{
Out << P.age << “ “ << P.name<< “ “ << p.sal;
Return out;
}
void main( )
{
Emp E, F;
cout << “ Enter age, name and sal”;
cin >> E;
cout << “Enter age, name & sal;
cin >> F;
cout << E << end1;
cout << F <<end1;

Q. What is the need of overloading insertion and extraction operator?


Ans:- In C++, all primitive types like int, float, char etc. are display on console
using predefined object cout along with insertion operator (<<).
Now if programmer wishes to use the same way of displaying objects of his
class on screen then he has to overload insertion and extraction operator so that
they can be derictly used with user defined objects.

Q. Why don’t we overload insertion and extraction operator as member function?


Ans:- Insertion and Extraction operator are binary operator and if binary operator
is overloaded as member function of class then a compulsion is their to keep the
object of same class towards left of operator while calling. Thus if it is done then
wll would become P << cout where P is object af class. Now this violotes the
regular symmetry of insertion operator and so it must be overloaded as friend
function.

Q. Equal Operator can never be overloaded as friend function.

Ans:- Since equal operator should return the reference of calling object (to support
coscading). It has to be overloaded as member function as friend function do not
have any calling object

Note:-
Equal operator if defined by base class never inherited by derive class
because it needs the same members in source as well as destination object.

TYPE CONVERSION

Type conversion is the process using a programmer can convert value from
primitive to non primitive and vice versa as well as from one object of class to
another object of different class.
Thus type conversion falls in three categories:-
1> Basic to User Defined
2> User Defined to Basic (Primitive )
3> User Defined to User Defined

Conversion Between Basic TO User Defined

Constructor (Basic type


{
// steps to convert basic to user defined
}

Conversion Between User Defined TO Basic

Operator primitive type of C++ ( ) return type


{
// steps to convert basic to user defined
Return (<basic – val>);
}

Example User To Basic & Basic To User

class Meter
{
float length;

public :
Meter ( )
{
Length = 0.0;
}
Meter (float cm)
{
Length = CM/100;
}
Operator float( )
{
Flaot ans= length * 100.0;
Return (ans);
}
void accept meters( )
{
cout << “enter length in (int meters)”;
cin >> length ;
}
void show meter( )
{
cout << “In meter = “ << length ;
}
};
void main ( )
{
Meter M1 = 250;
Meter M2;
M2.accept Meter( );
float cm = m2; // float CM= M2. operator float( );
cout << “250 Meters when converted”;
M1. show Meter( ); M2. show Meter( );
cout “ when converted to cms =” << cm
}

Program :- Asignment

class string
{
char str [10];
public:
string (int n)
{
Itoa (n, str, 10);
}
string( )
{
Str [0]= ‘\0’;
}
Operator int( )
{
K=1;
I= strlen (str);
While (i>=0)
{
Sum = sum + (str [i] -48)* k
K * = 10;
I - -;
}

Conversion From User Defined To User Defined

1. Conversion Routine In Source Object:-


Operator <destination_class-name> ( )
{
//routines to convert source to destination
Return ( <destination – object>);
}

2. Conversion Routine In Destination Object:-


Constructor ( <source – class – name>)
{
//routines to convert source to diction
}

Conversion From User Defined To User Defined By Placing Conversion Routine


In Source Object

class Radian
{
float rad;
public:
Radian ( )
{
Rad = 0.0;
}
Radian (float r)
{
Rad = r;
}
void show( )
{
cout << “Radian =” << rad << end1;
}
};
class Degree
{
float deg;
public:
Degree( )
{
Beg = 0.0;
}
Operator Radian ( )
{
float x = deg * PI/180;
Radian obj = x;
Return (obj );
}
void show( )
{
cout << “Degree=” << deg;
}
void getdagree( )
{
cout << “ enter angle in degree=”;
cin >> deg;
}
};
void main ( )
{
Degree D;
d. getdegree( );
Radian R;
R=D;
D. show( );
R. show( );
}

class Degree
{
float deg;
public:
Degree( )
{
Deg =0.0;
}
void show( )_
{
cout << “Degrees=” << deg;
}
void getdata( )
{
cout << “enter angle in degrees”;
cin >> deg;
}
Flaot getDree( )
{
Return (deg);
}
};
class Radian
{
float rad;
public:
Radian (Degree Obj)
{
Rad = obj.get Dece ( ) * PI/180;
}
Radian ( )
{
Rad=0.0;
}
void show( )
{
cout << “ Radian +” << rad;
}
};
void main( )
{
Degree D;
D.getData( );
Radian R = D; // Radian R (D);
D. show( );
R.show( );
}

Assignment:-

#include <iostream.h>
#include <conio.h>
class hour
{
float time;
public:
Hour( )
{
Time = 0.0;
}
Hour (double x)
{
Time =x/3600;
}
Operator float( )
{
float x = time * 3600;
Return(x);
}
void accept( )
{
cout << “enter time in hours”;
cin >> time;
}
void show( )
{
cout << “in hour =” << time;
}
};
void main( )
{
Hour t1=3600;
Hour t2;
T2. accept( );
float x = t2;
cout << “3600 when converted to hours=”;
T1.show( );
T2.shjow( );
cout << “when converted to sconds =” <<x;
Getch( );
}

CONSOLE I/O OPERATIONS


Unformatted Formatted

1. Unformatted I/O
(a) istream & get (char &) can be
(b) int get( ) called by cin
(c) istream & get (char *, int)

Example :- cin.get(ch);
Can read only characters
cin=cin.get( );

Istream & getline (char *, int num, char delimiter);


Istream & getline (char *, int num);

Example :-

void main ( )
{
char ch;
cout << “enter text and press enter to stop”;
cin. Get (ch);
While (ch ! =’\n’)
{
cout << ch;
cin.get(ch);
}
Getch( );
}

void main ( )
{
char country [20], capital [20];
cout << “enter country name:”;
cin.get (country,20); cin.getline (country, 20);
cout << “enter capital”;
cin.getline (capital, 20);
cout << “contry is “<< country << end1;
cout << “its capital = “<< capital << end1;
}

Note:- cin.getline (country, 20, *)

This will terminate after 19 character or on pressing *, nothing


will happen on pressing enter rey.

Functions Of Ostream class


(a) ostream & put (char)
(b) ostream & write (char *, int)
This will start from base add upto no. of integers given.

Example :-
void main( )
{
char str[ ] = { “programming “};
int I;
for (i=0; i<strlen (str); i++)
{
cout.put (str [i]);
cout << end1;
}
for (i=1; i<=strlen(str); i++)
{
cout.write (str, i);
cout << end1;
}
for (i=strlen (str) ; i>=1; i--)
{
cout.write (str, i);
cout << end1;
}
}

FORMATTED I/O

Function Description

(i)width( ) specifies required no of fields to be used for displaying


the output. This fn is used for alignment.
(ii) precision( ) specifies the no of values to be displayed after decimal pt

(iii) fill( ) specifies a character to be used to fill the unused area of


field. By default the fulling is done using spaces.

(iv) setf( ) sets the format flag to be used while displaying the
output.

(v) unsetf( ) clears the flogs set using setf & restones the default
settling.

Defining field Width

Prototype:- int width( )


Returns the current width.
int width (int)
Old width aurrent width

void main( )
{
cout. Width(4);
cout << 123;
cout.width(4);
cout. << 39;
cout.width(2);
cout << 2345
}

Setting Precision

Prototype :-int precision ( ) By default


int precision (int) precision is of 6 pt.

void main ( )
{
cout precision (2);
cout << 2.23 << end1;
cout << 5. 169 << end1;
cout << 4.003 << end1;
}
Output  2,23
5.17
4

Filling :-
int fill( )
int fill (char)

void main( )
{
cout.file ( ‘*’);
cout.precision(2);
cout.width(6);
cout << 12.53;
cout.width(6);
cout << 20.5;
cout. width(6);
cout << 2;
}
o/p  * 12.53* * * 20.5 * * * * * 2

Note
There is no need to set fill and precision again and again while width flag
must be set again and again.

Formatting With Flags & Bit Fields

1> setf  long self (log-setbits, long – field)

Flag-value (1st argument) Bit field (2nd Arguments Description


Ios : : left ios : : adjust field justifies the output on
left side.
Ios : : right ios : : adjeist field justifies the output in
sight align mennes.
Ios : : internal ios : : adjust field passing accurs between
the sign or base indicator
& the value when the
value fails to fill the
entire width
ios : : dec ios : : base field display the data in decimal
conversion
ios : : oct “ display the data in actor
ios : : hax “ display the data in hexadecimal
ios : : scientific ios : : float field user exponential floating
notation
ios : : fixed “ user normal floating notation

Example :-

void main ( )
{
cout.self (ios : ; left, ios : : adjust field);
cout.fill (‘*’);
cout. precision (2);
cout.width (6);
cout << 12.53;
cout.width (6);
cout << 20.5;
cout.witdth (6);
cout <<2;
}
12.53 * 20.5 * * 2 * * * * *

void main ( )
{
cout.self (ios : : internal | ios : : adjust field );
cout.field (‘*);
cout. precision (2);
cout. width (10);
cout << -420.53;
}
Output : - - * * * 4 2 0 . 5 3

Displaying Trailing Zeros & Plus Sign


Long self (long – setbits)
(i) ios : : show pint (for trailing zeros)
(ii) ios : : show pos (for plus sign)
void main ( )
{
cout.setf (ios : : show point);
cout.precision (2);
cout << 20.55 << end1; output
cout << 55.55 << end1; 20.55
cout << 20.40 << end1; 55.55
} 20.40

Example :-
void main ( )
{
cout.setf (ios : : showpoint);
cout.setf (ios : : show pos);
cout.setf (ios : : internal, ios : : adjust field);
cout.precison(3);
cout.width (10);
cout << 420.53;
}
Output 
+ * 4 2 0 . 5 3 0

Formatting Data Using Manipulators


Non Parameterised Manipulators

Manipulator Description

1. end1 terminates the line and transfers the cursor to next row.
2. dec set conversion base to 10.
3. bex set the conversion field to 16.
4. oct set the conversion field to 8
5. flush flushes the output screen

Example :-
1. WAP to read a number in decimal and display it in hxadecimal.
void main ( )
{
cout << “ enter number”;
cin a;
cin >> a;
cout << “ no is = “ << n << end;
cout << “ It’s hexadecimal value= “ << hex<<n;
cout. self (ios : : show base);
cout << a;
}
Output:- no is = 64
Its hexaslccimal value = 40 0x 40

Example :- void main ( )


{
int n;
cout << “enter number”;
cin >> nex>> n;
cout << “number= “ << n;
}

Parameterised Manipulators

Manipulator Description

1. setw (int) sets the field width


2. setprecision (int) sets number of digits to be displayed after decimal
pint
3. setfil (char) sets the character to be field
4. setbase (int) set the conversion base. Here possible value of int
are 8.10 and 16.
5. setiosflag (long) sets the format flag.
6. resetiosflag (long) resets the format flag.

Example :-
void main ( )
{
int n = 100;
cout << hex <<n << “ “ << dec <<n << end1;
float f = 122.3434;
cout << f << end1;
cout << setprecision (3);
cout << f << end1;
cout << setiosflag (ios : : internal } ios : : show base);
cout << hex << n << end1;
cout << setiosfloag (ios : : scientifie) << f << end1;
}

Output:- 64 100
122.34339 9
122. 343
0x0064
1. 2 2 3 c + 0. 2

Overloading [ ] Operator

class Array
{
int *P;
int n;
public :
Array (int size)
{
P=new int [size];
N=size;
}
int & operator [ ] (int i)
{
Return (* (p+i) );
}
void fil (int pos, int value)
{
* (p+pos) = value;
}
Array ( )
{
Delete [ ]p;
}
};
void main ( )
{
Array obj(5);
int x;
for (int i=0; i<5; i++)
{
cin >> x;
Obj.fill (I, x); or obj [i] = x
}
for (I = 0; i<5; i++)
{
cout << obj [i];
}
}

Overloading Of Operator ( )

class Box
{
int l, b, h;
public:
Box operator ( ) (int, int, int);
void get( )
{
cout << “enter l, b and h”;
cin >> l >> b >> h;
}
void show( )
{
cout << l, << “ “ << b << “ “ << h;
}
};
Box Box : : Operator (int l, int b, int h)
{
Box temp;
Temp.l = l + this  l;
Temp.b = b + this  b;
Temp.h = h + this  h;
Return (temp);
}
void main ( )
{
Box B1;
B1.get( );
Box B2;
B2 = B1 (5, 3, 9); // B2 = B1. operator ( ) (5, 3, 9);
B1. show( );
B2. show( 0;
}

GRAPHICS MODE PROGRAMMING

Steps Required for Designing Graphics Mode Program

1> Concert the display monitor from text mode to graphics mode.
2> Perform the required graphics operation like filling coloring, drawing etc.
3> Finally close the graphics mode and restore character mode.

Converting Character To Pixels

1. void init gragraph (int *, int *, char *)


Driver resolution path of BGI file
Or
Mode
2. Drawing using built in functions.
3. void close graph( );
void restorecrtmode( );

Program:- WAP to couvert monitor display mode from char to pixel and print
welcome message.

#include <graphics.h>
#include <conio.h>
#include <stdlib.h>
void main( )
{
int gd, gm, ec;
Gd= DETECT;
Inttgraph (&gd, &gm, “C:\\TC\\BGI”);
Ec= graphresult( );
if (ec!=grOk) or (ec!=0)
{
Printf (“error in initialising”);
exit(1);
}
Cleardevice
Outtext ( “welcome to graphics”);
Getch( );
Closegraph( );
Restarectmode( );
}
Note:-

int getmaxx( ); returns the maximum value of x – coordinate.


int getmaxy( ):- returns the minimum value of if – coordinate.

Assignment:- Modify the above code so that now code display the
Message at the necter of screen.

void main ( )
{
int gd, gm, ec;
Gd = DETECT;
Initgraph (&gd, & gm, “C:\\TC\\BGI”);
Ec=graphresult( );
if (ec ! = grOk)
{
Printf ( “error”);
exit(1);
}
Cleardevice( );
int a = getmaxx( );
int b = getmaxy( );
Outtextry ( ( a/2), (b/2), “welcome to graphics”);
Getch( );
Closegraph( );
Restorecrtmode( );
}

Q. WAP to accept user name & then convert screen to graphics mode & display
the name given by user at the center of the screen on char at a time.

void main ( )
{
char str[20]
int gd, gm, ec;
Gd = DETECT;
Initgraph (&gd, &gm, “c:\\TC\\BGI”);
Ec = graphresult( );
if (ec!=grOk)
{
Printf ( “error”);
exit(1);
}
Cleardevicl ( ); printf (“enter name”);
Move to (getmaxx( ) /2, getmaxy( )/2);
for (i=0; str[i]; i++)
{
Spritf (msg, “%c”, str[i]);
Out text (msg);
Delay (1000);
}
}
Changing the font style and size

1. void settextstyle (int font, int dir, int charsize)


description of parameters

font  default – FONT (0)


TRIPLEX – FONT (1)
SMALL – FONT (2)
SANS – SERIT – FONT (3)
GOTHIC – FONT (4)
SCRIPT – FONT (5)
SIMPLEX – FONT (6)
PRIPLEX – SCRIPT – FONT (7)
COMPLEX – FONT (8)
EUROPEAN – FONT (9)
BOLD – FONT (10)

Dir  horiz – dir (0)


Vert – dir (1)

Charsize :- 1 to 10
1 being size of 8 x 8 pixel.

Program:-
void main( )
{
char * font – style [ ] = { “ Defualt – font” ----, “BOLD-
FONT”);
int gd, gm, ec; char msg[20];
Gd = DETECT;
Initgraph (&gd, &gm, “C: \\ TC\\ BGI”);
Ec = graphresult ( );
if (ec ! = 0)
{
Printf ( “error”);
exit (1);
}
Cleardevicl ( )
Move to (getmaxx( )/2, getmaxy( )/2);
for (1=0; i<=10; i++)
{
Printf (msg = “shiv - %s”, font-style [i]);
Settext style (I, 0, 1);
Outtextry (getmaxx( )/2, getmaxy( )/2, msg);
Getch( );
Cleardevicl ( );
}
Cleardevicl( );
Restorecrtdevicl ( );
}

DRAWING IN GRAPHICS
1. for Drawing Line:-

a. void line (int x1, int y1, int x2, int y2)
b. void linerel (int, int)
c. void line to (int, int)

Example :-
void maiN ( )
{
int gd, gm, ec, x, y;
Gd = DETECT;
Initgraph ( &gd, &gm, “ c: \\TC\\BGI”);
Ec = graphresult( );
if (ec ! = 0)
{
Printf ( “error”);
exit (1);
}
Cleardevicl ( );
X=getmaxx( )/2; y=getmaxy( )/2
Line (0, 0, x, y);
Getch ( );
Closegraph( );
Restorertmode( );

Q.WAP which draws a line from 20, 30 to 100 pixels further & display the
wordinate of line at its end point.

void main ( )
{
int gd, gm, ec, x, y;
Gd = DETECT;
Initgraph (&gd, & gm, “c: \\TC\\BGI”);
Ec = graphresult ( );
if (ec! = 0)
{
Printf ( “error”);
exit (1);
}
Cleardericl ( );
Move to (20, 30);
Sprintf (msg, “%d %d”, get x( ), gety( ) );
Outtext (msg);
Linerel (100, 100);
Sprintf (msg, “%d %d”, getx( ), get y( ) );
Outtext (msg);
}

Drawing Linee In Specific Width & Style

void setline style (int style, int pattern, int thickness)

Style:- No Constant meaning


0 SOLID-LINE solid line
1 DOTTED –LINE
2 CENTER-LINE line withdot & dash
3 DASHED-LINE line with dashes
4 USERBIT-LINE

Pattern:- It is always zero except when first parameter is userbit line.

Thickners:- 1 – THICK-WIDTH
3 – NORM-WIDTH

void main( )
{
int gd, gm, ec, I;
char * style [ ] = { “solidline}, Dotted-line”,----, “Dashedline”};
Gd = DETECT;
Initgraph ( &gd, & gm, “C: \\TC\\BGI”);
Ec=graphresult( );
if (ec != grok)
{
Printf ( “error”);
exit(1);
}
Deardvice( );
for (i=0; i<4; i++)
{
Spritf (msg, “%s in normal width”, style[i]);
Outtext (getmaxx( )/2-20, getmaxy( )/2-10, msg);
Setlinestyle (I,0, NORM-WIDTH);
Line (getmaxx( )/2-50, getmaxy( )/2 +20, getmaxx( )/2 +50,
Getmaxy( )/2 +100);
Getch( );
Cleardevicl( );
}
Restorectdevicl( );
}

Defining Pattens in User Defined Way


Io define a user bit line wee have to build a sixbit pattern. In this pattern
wheever a bit is one the curresposing pixel in the line is drawn in the current
drawing colour.
for eg:- 65535
or
setline style (4, OXFFFF, NORM-WIDTH);
this will draw a solid line,
setlinestyle (4, Ox3333, NORM-WIDTH)
this will draw a dashed line.

Drawing Arcs Or Circles Or Rectangles

1. void arc (int x, int y, intstangle, int endangle, int rad)

2. void piesline (int x, int y, int stangle, int endangle, int rad)

3. void circle (int x, int y, int rad)


4. void rectangle (int left, int top, int right, int bottom)
5. void bar (int left, in top, int right, int bottom)

Filling Image With Different Patterns


void set color (int)
void setfillstyle (int pattern, int style)

Pattern:- The pattern parameter signifies the pattern in which filing is to be


made.

Name value Result


1. Empty Fill 0 Background color

2. SOLID-FILL 1 Solid Filling

3. LINE-FILE 2 --------------
-------------

4. LISLASH_FILE 3

5. SLASH-FILL 4

6 BKLASH-FILE 5

7. LTBKSLASH-FILE 6

HATCH-FILE 7

XHATCH-FILE 8

INTERLEAVE-FILE 9

WIDE-DOT-FILE 10

CLOSE-DOT-FILE 11

WAP which draws a sectangle with white outline & red fill color & should display
the fitling in all of the twelve patterns one at a time. Also name of pattern should
be displayed with in the rectangle.

void main ( )
{
int gd, gm, ec, left, right, top, bottom, I;
char * style [ ] = { “EMPTY-FILE”, “SOLID-FILE”, ----,
CLOSED-DOT-FILE”};
Gd=DETECT
Initgraph (&gd, &gm, “C:\\TC\\BGI”);
Ec=grapgresult( );
if (ec !=0)
{
Printf (“error”);
exit (1);
}
Cleardevicl ( );
Left = getmaxx( )/2-100;
Top=getmaxy( )/2-100
Right – getmaxx( )/2+100;
Bottom=getmaxy( )/2;
for(i=0; i<12; i++)
{
Setfill style (I, RED);
Bar(left, top, right bottom);
Rectangle (left, top, right, bottom);
Outtextxy (left+50, top+50, style[i]);
}
}

FILLING CIRCLES & TRIANGLESS

1. void floodfill (int x, int y, int boundary)


(x, y)  a point with in the figure which has to be filled using flodfill also known
as sad.

Boundary color:- Color at which filling should stop.

Filling Circles With Different Pattern

void main ( )
{
char * pattern = { “EMPTY-FILE”, --------, “CLOSE-DOT-FILE”};
int gd, gm, ec, x, y, 0;
Gd=DETECT;
Initgraph (&gd, &gm, “C:\\TC\\BGI”);
Ec=graphresult( );
if (ec! = grOk)
{
Printf ( “error”);
exit(1);
}
Cleardevice( );
X=getmaxx( )/2; y=getmaxy( )/2;
for (i=0; i<12; i++)
{
Setcolor (GREEN);
Circle (x, y, 100);
Setfill style (I, RED);
Floodfill (x, y, GREER);
Setcolor (WHITE);
Outtextxy (x-50, y-50, patter[i]);
Getch( );
Cleardivice( );
}
Getch ( );
Restorecrtdevice( );
}

Storing and Drawing Images On Screen

1. void getline (int, int, int, int, void *)


2. int imagesize (int, int, int, int)
3. void putimage (int, int, void *, int option)

void getimage (int, int, int, int, void *)


copies the bit image of specified
postion in memoery

1st parameter indicates  left coordinates


2nd parameterer  to “
rd
3 parameter  right “
th
4 parameter  bottom “
5th parameter  pointer to an array large enough to store bit pattern.

void putimage [int x, int y, void * are, int iption)


Copies or outputs the image pattern form memoery to the specified
portion on the screen.

X = starting left coordinate


Y = starting top coordinate
Arr = maner un which color of the resultant pixel is to be decided, taking into
consideration the pixels stored in memory & the pixels stores on screen.

int image size (int, int, int, int);-


Returns no. of bytes required to store the image, on any kind of error
return -1

void main ( )
{
int gd, gm, ec;
char * buffer, msg [20];
int size -0f-image;
Gd = DETECT;
Initgraph ( &gd, &gm, “C:\\TC\\BGI”);
Ec = graphresult( );
if (ec ! =0)
{
Printf (“error”);
exit (1);
}
Rectangle (150, 150, 200, 200);
Size-of-image = image size (150, 150, 200, 200);
if (size-of-image = = -1)
{
Outtextxy (getmaxx( )/2, getmaxy( )/2, “Error”);
Getch( );
Close graph( );
exit(1);
}
Buffer = (char *) malloc (size-of-image * size of (char) );
if (buffer = = NULL)
{
Outtextxy (getmaxx( )/2, getmaxy( )/2, “Can not allocate memory”);
Gecth( );
exit(1);
Close graph( );
}
Getimage (150, 150, 200, 200, buffer);
Line (200, 220, 220, 220);
Putimage (175, 200, buffer, COPY-PUT);
Getch( );
Closegraph( );
Restore crtdevice( );
}

VALUES CREEN EMORY OUTPUT


COPY-PUT ON ON ON
OFF ON ON
ON OFF OFF
OFF OFF OFF

XOR-PUT ON ON OFF
OFF ON ON
ON OFF ON
OFF OFF OFF

OR-PUT ON ON ON
OFF ON ON
ON OFF ON
OFF OFF OFF

AND-PUT ON ON ON
OFF ON OFF
ON OFF OFF
OFF OFF OFF

THE END

You might also like