Beruflich Dokumente
Kultur Dokumente
C++
#include <stdio.h>
Function <printf
Scanf
#include <iostream.h>
cout. in are objects
cout << Hello;
Insertion operator
Or
Insertors
cout << value = <<a;
No need of format specefiers
In C++
cin >>a;
Extraction operator
Or
Extractor
cin >>a >>b;
Cascading of extractor;
HISTORY OF C++
Year 1982
Developed By Bjarne stroustrap
Lab Bell Labs
Company At & T
roll
get
s
show
grade
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)
1. objects
2. data members
3. member function
4. function call
OOPs (Terminology)
instances
properties & attributes
methods & behaviors
message passing
member function of an existing class in his own class with the help of
inheritance. The class which gets inherited is known as base class and the
class which inherits is known as derived 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 reusability 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.
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 dont 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 cant be declared as static
5. They cant 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 contructors 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;
cin >> 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
1. No. of Arguments
2. Type of Argument
3. Order of argument
int show ( )
Not allowed (return type differs)
void show( )
Compiler does not consider return type, because it is not compulsory to receive the
value returned by the function. Thus compiler will not be able to differentiate for
which function the call is being made. Function overloading allows same function
name in same scope but there should be some difference 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 & incresage the readability of program
CONSTRUCTOR OVERLOADING
class Box
{
int l, b,h;
public:
Box( ); //constructor for user defined Box
COPY CONSTRUCTOR
It is a special constructor of a class which accepts the reference of the object of its
own class as a parameter. It is called by c++ compiler in there situations
1. when ever programmer creates an object and at the same time passes another
object of the same class as a parameter
Drawbacks of pointer
1. will be initialized by garbage
2. necessary to initialize before their use
3. very careful in using indirection operator
Advantage of Reference variable
1. we can have n reference variables of one
variable
2. both variables get interlocked on each
Other
3. does not require any memory space it
Only reuse the memory of any variable
C/C++
C/C++
pass by value
pass by address
void swap (int, int);
void swap (int*, int*);
void main( )
void main( )
{
{
int a,b;
int a,b;
cout << Enter2 number; cout << Enter2no;
cin >>a>>b;
cin >> a >> b;
swap (a,b);
swap (&a, &b)
cout << a << <<b;
cout <<a<< <<b;
}
}
void swap(int p,intq)
void swap (int*p, int*q)
{
{
int temp;
int temp;
temp =p;
temp=*p;
p=q;
*p=*q;
q=temp;
*q= temp;
}
}
only in C++
pass by reference
void swap (int&,int&);
void main( )
{
int a,b;
clrscr( ) ;
cout << enter2no)
cin>>a>>b;
swap (a,b);
cout <<a<< <<b;
}
void swap(int&p,int&q)
{
int temp;
temp=p;
p=q;
q=temp;
}
Q. WAP to use a function call maximum which accepts an integer array of size
pure as an argument & return the largest & smallest element of that array to main.
Without changing the original position of element of 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 B4 (B1)
Box B2 = 10;
Box B4 = B;
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 =
}
void main( )
{
Stud t ( 15, A, 75);
Stud p;
p. get( );
t. show( );
p. show( );
}
<<per;
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 tilde (~). They are automatically called whenever an
object goes out of scope, that is ,it is about to be destroyed
When an object is created first function which is automatically called is
constructor & when object ends its life the last function which is called is
destructor which can be used to deallocate the resource occupied by the object.
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:- Destructors 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 dont 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
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 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
1.auto
garbage
(automatic)
2. static
Zero
3. register
4. global
garbage
zero
Auto
void display ( );
void main( )
{
display( );
display ( );
display ( );
}
void display( )
{
int a;
cout <<a<<end1;
a++;
life
limited to
their
Declaration
Block
throughout
The program
same as auto
throughout
The program
scope
limited to declaration block
same as auto
throughout the program
Static
void display ( );
void main ( )
{
display( );
display ( );
display( );
}
void display( )
{
static int a;
cout <<a<<end1;
a++;
}
o/p 0
1
2
STATIC DATA
0
a
b
a
int data : : b;
d1
D2
static variable dont 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);
{
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;
}
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;
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 thisl=l;
b=j;
thisb=b;
h=k;
thish=h;*/
}
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
Const variable
pointer to const
const pointer
const pointer to const variable
const parameters
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 cant 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* 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;
}
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.
}
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( );
}
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)
{
++ c.count
return (C);
}
Or
counter temp;
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
dont 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);
}
II
D2 = D1+n;
// can be done using member fn & friend fn
D2. show( );
cout << Enter an integer;
cin >>n;
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
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( )
{
NEW
It is a operator
header file not required
It takes no. of elements
Required as parameter
bring has no such memory store
New has no such memory
limitation
New automatically converts
according to the datatype given
thus no need to explicitly type
cast its return value.
int * P;
P= new int (10);
cout << *P;
delete P;
2000
P
2.
int *P;
P=new int [10];
delete [ ] P;
3000
P
10
2000
2002
3000
1.
2.
Eg:-
delete <ptr-name>;
delete [ ] <ptr-name>;
float *P;
delete P;
}
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;
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;
}
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
for (i=0; i<n; i++)
(p+i) show( );
or
getch( );
delete[ ]p;
}
p[i]. get( );
p[i]. show( );
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( );
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
A
Base class
Derived class
base class of C
c
3. Multiple Inheritance
A
4. Hierarchial Inheritance
D
Syntax for Inheritance:class <class name>: public / private / protected < clas-name>
Derived class Mode of Inheritance
class Box
{
int l, b, h;
public:
void get( )
{
cout << enter l, band;
Base class
};
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)
(ii)
(iii)
function name or
calling object type or
function parameter type
in other words early binding is always in action in normal fn calls,
overloaded fn calls and overloaded operators
Overloading
always in same class
means at single level
Prototype of functions
Must be same .
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( );
}
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;
}
};
input
display
sort in ascending
sort in descending
quit
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:
case 4:
sr.ascsort( );
break;
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( );
Error ambiguity
error
}
};
void main( )
{
Drv obj;
obj. accept( );
obj. add( );
obj. print( );
}
base1: : show( );
base2: : show( );
};
class drv: public Base
{
public:
drv( )
{
cout << In derives 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;
}
};
base2
drv
int a;
Base1 (int);
void show( );
int b;
base2 (int);
void display();
int c;
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)
(ii)
(iii)
{
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( );
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;
}
GRANTING 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 drvs 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 bases show;
}
};
class drv1 : public Base
{
public :
void show( )
{
cout << In drv1s show;
}
};
class drv2: public drv1
{
public:
void show( )
{
cout << In drv2s 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 bases 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.
VTABLE FOR A
&A : : f2( )
&A : : f3( )
VTABLE FOR B
&B : : f2( )
&A : f3( )
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 Inheritance
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( );
}
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:
public:
int *p;
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.
Monitor
Input stream
output stream
C++ Program
Input stream
output stream
Hard-disk
Hard disk
(a)
(a)
(b)
Step 4
Of stream obj;
obj. Open ( Data. Txt);
obj << Hello;
obj. put (H);
obj.close ( );
static data
File Opening Mode
isopen ( )
Returns 1 if conceted
0
1
Fail( )
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
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
BINARY I /O
void
write
Of stream
Member
(char *,
address of variable
whose data is to be
Written
int )
no of bytes 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
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)
{
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;
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 ( );
S1. resetstring ( Welcome);
S1. display ( );
S2. display( );
}
{
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 dont 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
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
}
// Radian R (D);
Formatted
can be
called by cin
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:-
FORMATTED I/O
Function
Description
(i)width( )
(ii) precision( )
(iii) fill( )
(iv) setf( )
(v) unsetf( )
clears the flogs set using setf & restones the default
settling.
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
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;
cout << 55.55 << end1;
cout << 20.40 << end1;
}
Example :-
output
20.55
55.55
20.40
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
+
Description
Output:-
no is = 64
Its hexaslccimal value = 40 0x 40
Description
sets the field width
sets number of digits to be displayed after decimal
pint
sets the character to be field
set the conversion base. Here possible value of int
are 8.10 and 16.
sets the format flag.
resets the format flag.
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;
}
Cleardevice
Outtext ( welcome to graphics);
Getch( );
Closegraph( );
Restarectmode( );
}
Note:int getmaxx( );
int getmaxy( ):-
Assignment:-
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]
Dir
Charsize :- 1 to 10
1 being size of 8 x 8 pixel.
Program:void main( )
{
char * font style [ ] = { Defualt font ----, BOLDFONT);
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);
}
Constant
SOLID-LINE
DOTTED LINE
CENTER-LINE
DASHED-LINE
USERBIT-LINE
Pattern:-
Thickners:-
meaning
solid line
line withdot & dash
line with dashes
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)
Name
1. Empty Fill
value
0
Result
Background color
2. SOLID-FILL
Solid Filling
3. LINE-FILE
--------------------------
4. LISLASH_FILE
5. SLASH-FILL
6 BKLASH-FILE
7. LTBKSLASH-FILE
HATCH-FILE
XHATCH-FILE
INTERLEAVE-FILE
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]);
}
}
rd
3 parameter
right
th
4 parameter
bottom
th
5 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
COPY-PUT
CREEN
ON
OFF
ON
OFF
EMORY
ON
ON
OFF
OFF
OUTPUT
ON
ON
OFF
OFF
XOR-PUT
ON
OFF
ON
OFF
ON
ON
OFF
OFF
OFF
ON
ON
OFF
OR-PUT
ON
OFF
ON
OFF
ON
ON
OFF
OFF
ON
ON
ON
OFF
AND-PUT
ON
OFF
ON
OFF
ON
ON
OFF
OFF
ON
OFF
OFF
OFF
THE END