C++ Notes Complete
C++ Notes Complete
C++ Notes Complete
HISTORY OF C++
Year 1982
Developed Bjarne stroustrap
Lab Bell Labs
Company At & T
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;
}
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.
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:-
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:
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
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.
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:-
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
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.
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 B4;
B4 = B1
No call for copy constructor use of assignment operator other
destination object is already made.
DEFUALT ARGUMENTS
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
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 *;
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);
}
}
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
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( );
};
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
1. Default value
2. life (persistence)
3. scope (accessibility)
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);
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( );
};
“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( );’
}
“this” POINTER
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 thisl=l;
b=j; thisb=b;
h=k; thish=h;*/
}
void Box : : show( )
{
cout << l << “ “ <<b<< “ “ <<h;
cout << this l << thisb << this h;
}
void main( )
{
Box B1;
Box B2 (5, 7, 11);
Box B3 = B1;
B1. show( );
B2. show( );
B3. show( );
}
LIMITATIONS OF THIS
Box = *q;
Q = this+1 // valid
Q=++this // not valid
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.
“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
}
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,
Here the strlen function is prevented from modifying the string that p points to.
<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;
}
};
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 .
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
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* pb* ph;
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”;
}
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
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( );
}
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( );
}
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
Syntax:-
<ret-type> operator <op-symbol> (arguments);
friend (ret-type> operator <op-symbol> (<arguments>);
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 ( );
}
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( );
}
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;
}
};
void main()
{
counter c1=10,c2;
c1.show();
c2=++c1;
c1.show();
c2.show();
getch();
}
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 ( );
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
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
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.
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.
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
3000 ..
P 3000
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.
DYNAMIC OBJECTS
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;
}
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);
}
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
A B A
C B C
A
B C
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( );
}
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:-
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
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 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;
}
};
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 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
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;
}
};
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;
}
};
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;
}
};
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( );
}
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;
}
};
Note :-
if the constructor of base class is parameterized then
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 :-
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;
}
};
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( );
}
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.
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.
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
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;
}
};
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.
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.
C++ Program
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);
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( );
}
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;
}
}
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.
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
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.
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( );
}
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:-
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);
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( );
}
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 :-
Example
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
Q. write a function template which accepts two values as an argument & return
maximum amongst then.
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.
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
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( );
}
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
Note :-
for cascading of assignment operator it is necessary that return type must be
string
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.
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;
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
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 - -;
}
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( );
}
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( );
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;
}
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
(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.
void main( )
{
cout. Width(4);
cout << 123;
cout.width(4);
cout. << 39;
cout.width(2);
cout << 2345
}
Setting Precision
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.
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
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
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
Parameterised Manipulators
Manipulator Description
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;
}
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.
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:-
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
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);
}
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( );
}
2. void piesline (int x, int y, int stangle, int endangle, int rad)
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]);
}
}
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( );
}
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( );
}
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