Sie sind auf Seite 1von 144

C

#include <stdio.h> Function <printf Scanf

C++
#include <iostream.h> cout. in are objects cout << Hello; Insertion operator Or Insertors Cout << value = <<a; No need of format specefiers In C++ in >>a; Extraction operator Or Extractor In >>a >>b; Cascading of extractor; cout << Hello \n User; Or Cout << Hello <<end <<User; in C++ default return type is an integer

Scanf ( %d, &a);

For next line Printf ( Hello \n user);

In C, default return type Is void

HISTORY OF C++
Year 1982 Developed Bjarne stroustrap Lab Bell Labs Company At & T C is procedure oriented language Easy & fast programming in C. Logics can be easily developed Developed. C is object oriented language C++ closely models sear world problems

CLASSES AND OBJECTS


In structure of C :- only data can be member of structure and not functions All member of structure of are public by default In class of C++ data + functions accessing those data are member of class and All member of class are private by default Class stud { Int roll; Char grade; Float par; Public: Void get( ); Void show( ); }; Void stud : : get( ) { Cout << enter roll. Grade and per; Cin>>roll>> grade >> per; } Void stud : : show { Cout <<roll << << grade << <<per<< end1; } Void main( ) { Stud s; S. get ( ); s. show( ); } get show roll 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

BASIC PRINCIPLES OF OOP


ENCAPSULATION Word has been derived from a word capsule which means multiple medicines packed in one single unit. Similarly in a software there are two major unit data & functions acting on that data since functions and data are related entities it is advisable to score them within a single unit. Thus according to oops Encapsulation means building or wrapping up of data members and f n acting on those data members with in a single unit. Since a class allows us to hold data & functions within it are say that it supports the principle of encapsulation. POLYMORPHISM The word polymorphism is derived from combination of two words poly mcarning multiple and morph means the ability to have multiple forms. In other words if an entity can acquire multiple forms in different situation we say that its behaviors is polymorphic for eg in c++ it is possible for programmer to redife operator + in such a way that it can be used to add two integers as well as at the same time it can add two abject or two strings. So it a programmer define + to behave in above mentioned member we say that + behaves polymorphically . In C++, polymorphism is implemented in two way:(1). Compile time polymorphism :- function overloading and operator Overloading (ii). RunTime polymorphism:- Virtual functions, pure virtual functions Ads tract classes (iii). Inheritance :- to inherit means to acquire properties and fea of an Existing entity into a newly created entity Like a child acquire properties of his or has Parent, similary when designing software if a programmer wishes then he can acquire the fratures (data and member function) of an existing class in his own class with the help of inheritance. The class which gets inherited is known as bass class and the class. Thus by inheriting the members of base class it becomes possible to access them through the objects of derive class. The major advantage offered by principle of Inheritance is rcusability and reliability

CREATING PARAMETERIZED FUNCTIONS WITHIN CLASSES Class Emp { Int age; Char name[20]; Float salary; Public: Void set (int, char *, float); Void show( ) }; Void Emp: : set (int I, char *j, float K) { Age =I; Strcpy (name, j); Salary =k; } Void Emp : : show( ) { Cout <<age << <<name << salary; } ASSIGNMENT Wap to create a class c/a string. The class must contain a character array of size 20. class should have following fucnitons: (1). Getstring( ) which accept string as parameter + stores it in array str. (2). Show string( ) which display the string stored in str[]. (3). Reversestring ( ) which reverses the string stored in str[]. (4). Add string( ) which accepts string as parameter and if possible Concatenates in str. Write an object oriented program to calculate the factorial of a given by user. Provide separated function for initialization, inputting, calculating and display. Class Fact {

Int I, 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*:; } Void fact : : display( ) { Cout << Number = << n; Cout << factorial= <<f; } Void main( ) { Fact obj ; Obj. init( ); Obj.getno( ); Obj.get calculate( ); Obj. display( ); }

CONTRUCTOR
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 contractors are destroyed as soon as we declare constructor Example :Class fact { Int I, b; Public: Fact( ) { F=1; } Void getno( ); Void calculate( ); Void display( ); }; Void fact : : getno( ) { cout << enter a no; an >> n; }

Void fact : : calculate( ) { 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( 0; }

PARAMETERIZED CONSTRUCTOR
Class Emp { Int age; Char name[20]; Flaot 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; }

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, other wise constructor can never be overloaded as they have no returns type. Function overloading allows some function name in same scope but there should be some different in functions. Void vol (int); Void vol (int, int, int ); Void main ( ) { Int choice; Cout << select a figure; Cout << (1) cube \n (2) cuboid; cin >> choice ( ); Swith (choice) { Case 1: Int s; Cout << enter side of cube; Cin >> s; Vol (s); Break; Case 2: Int l.\, b, h; Cout << Enter l, band h of alboid; Cin >> l >> b >> h; Vol (l,b, h); Breck; Default: Cout < wrong choice; Void show (int, int, int) void show (int) void show (double) void show (int, double) Void show (double, int)

} Void vol (int s) { Cout << value of cube = << s*s*s; } Void vol (int l, int b, int h) { Cout << value of alboid= << l*b*h; } ADVANTAGES OF FUNCTION OVERLODING 1. Overload of remembering the name is transformed from programmer to compiler 2. it develops symmetry & incrrases the readability of program CONSTRUCTURE OVERLOADING Class Box { Int l, b,h; Public: Box( ); //constructor for user defined Box Box (int); //constructor for albe }; 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 B2 (10); B1. show( ); B2. show ( ); B3. show ( ); }

COPY CONSTRUCTOR
It is a special constructor of a class which accepts the reference of the object of its our class as a parameter. It is called by c++ compiler in there situations 1. when ever programmer created an object and at the same time passes another object of the same class as a parameter 2. whenever a f n accepts an object as a parameter by value. 3. whenever a f n returns an object by value. Reference variable:Syntax:- <data type> & <sef-name> = <var-name>; Void main( ) { Int a = 10; Int *p; P=&a; Cout <<*p <<end1; } Void main ( ) { Int a=10; Int &p=a; prowbacks of pointer 1. occupy 2 bytes of memory 2. will be initialized by garbage 3. necessary to initialize before their use 4. very caseful in using indirection operator Advantage of Reference variable 1. we can have n reference variables of one variable

Cout <<a<< <<p; Cout << &a << <<&p;

2. both variables get interlocked on each Other 3. does not require any memory space it Only reuse the memory of nay variable

Reference variable is a technology provided by c++ which allow a programmer to create anew variable which stores (not holds) the memory location of an existing variable. In other words, reference variable is a technique using which programmer can allot multiple mames to same memory location. POINTER TO REMEMBER 1. int &p = a; 2. int 7p =; multiple declarations for the variable p. 3. In case of array, always use pointer. Reference variable can not work with array 4. we can not make array of reference variable int &p [4] C C pass by value pass by reference void swap (int, int) void swap (int*, int*) void main( ) void main( ) 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; } } C++ pass by reference void swap (int7,int&) void main( ) { int a, b; cout << enter2no) cin>>a>>b; swap (a,b); cout <<a<< <<b <<end1; } void wsap(int&pint&q) { int temp; temp=p; P=q; Q=temp; }

Note :- By call it is not possible to call whether it is call by value or call by reference Q. WAP to use a function call maximum which accepts an integer array of size pure as an argument & retirns the largest & smallest element of that array to main. Without changing the arcginal position of element of ht array. 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 & main) { Int f; Max = a[0]; Min=a[0]; For 9j=1; j<5; i++) { If (* (a+j) >max) Max=* (a+j); Else if (* (a+j) <min) Min = *(a+j); } } 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 B=p.b; b1s l, b,h. 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 ( ) B2. show( ) { Box B1; B3. show( ); Box B2 (10); B4. show( ); Box B2 (5,7,11); } Box B4 (B1); B1. show( 0; Box B2 (10) Box B4 (B1) Box B2 = 10; Box B4 = B;

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

DEFUALT ARGUMENTS
Void printline (char =*, int=1) Void main ( ) { Printline ( ); // printline (*, 1) Printline (#); // printline ( #, 1) Printline (!, 10) // printline (1, 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; Char j; Per k;

} Void std : : get( 0 { Cout << Enter age, grade & per ; Cin >> age >> grade >> per; } Void stud : : show( 0 { Stud main( ) { Stud t ( 15, A, 75); Stud p; p. get( ); t. show( ); p. show( 0; } Note:- In class at same time it is not possible to have default argument constructor and default constructor.

DESTRUCTOR
Are special member f n of class which have same name as that of the class but preceded with the symbol of field ( ). They are automatically called whenever an object goes out of scope & is about to be destroyed When an object is created first function which is automatically called is constructor & when object ends its life a last function is called to free occupied memory is destructor Class Emp { Int age; Char name [20]; Float sal; Public: Emp( ); Emp( ); Void show( 0; };

Emp : : emp( ) { Cout << Enter age, name & sal; Cin >> age >> name >> sal; } Void emp : : show( ) Note { A class by default has 3 built in Cout <<age << name <<sal; fucntion } 1. Constructor Emp : : Emp( ) 2. copy constructor { 3. Destructor Cout << Object destroyed; } Note:- Destructor are always called in Void main( ) reverse order. { Emp e, f,; E. show( ); f. show( ); } Create a class c/o student having 3 data members (i) for storing Roll no. (ii) for storing name (iii) for storing marks in subjects The member for storing name should be char *, member for storing marks should be int *; Create constructor of class which prompts user to enter length of name, allocates sufficient memory & accepts the name from user. The same constructor asks the user how many subject he want to enter, againallocate sufficient memory for that & accepts the marks given by user. Finally provide appropriate member f n which display % & grade of student. At the end define the destructor in proper manner to deallocate memory allocated by constructor. Class student { Int roll non; Char * name, grade; Int *marks; Float per;

Public: Student ( ); Void get( 0; Void calculate( ); Void show( 0 Student ( ) } Student : : student ( ) { Cout << how many letters; Cin >>n; Name = (int *) malloc (n+1) * size of (char)); If (p= = null) Exit(1); Get( ); } Void student : : get( ) { Cout << enter roll no; Cin >> roll ; Cout << enter name; Cin >> name; For (i=0; i<n; i++) { Cout << Enter marks; Cin >> * (q+i); } } Void student : : calculate ( ) { Per=0; For (int i=0; i<n; i++) Per+= * (q+i) Per / = n; If (per >=75) Grade = A; Else if (per >=60) Grade = B;

Else grad = f; } Student : : student ( ) { Free (Q); Free(p); } Void student : : show( ) { } Void main( ) { Student 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 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

2. 3.
4.

5. 6. 7.

preceded with the symbol of tilde 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. we can not pass parameters to a destructor. as they dont accept parameters we can not overload then, thus a class can not have multiple destructor calling of destructor is always done in reverse or des of the creation of objects. inheriting of destructor is also not possible we can have virtual destructor in a class.

INLINE FUCNTIONS
Inline functions Are those fn whose call is replaced by their body during compilation. Declaring a fn as inline has two major advantages.
1. compiler does not has to leave the calling fn as it finds definition of fn

being called their it self. 2. The overhead of maintaing the stack in belureen function call is seduced Thus declaring a function as inline increases the execution Speed, s\reuces execution time & thus enhances the overall efficiency of program. But two ptr must be considered before declaring a fn as inline
1. The definition of inline function must appear before its call i.e. if a non

member fn is to be made inline then its declaration & definition must appear about main as a single unit. 2. the body of inline fn must be short & small 3. it should not contain any complex keywords or keyword or statement like for, if, while, dowhile do,

if any of the aboul sules are violated then compiler ignores the keyword inline an treats the fn as offline or normal one. Moreover a class can have two kinds of inline functions 1.Implicit Inline :- fn efined within the body of class 2. Explicit Inline :- fn declared within the class but defined outside the class preceded with the keyword inline. Thus at the end we can say, that declaring a fn as line is a request made by programmer which the later may agrel or deny. Class Emp { Char name [20]; Int age; Float sal; Public : Void get( ) Implicit { Inline cout << enter age, name and sal; Cin >> age >> name >> sal; } Void show( ); }; Explicit Inline inline void Emp : : show( ) { Cout << age << <<name << <<sal; }

Void main( ) { Emp E[5]; Int I; For (i=0; i<5; i++) E[i]. get( ); For (i=0; i<5; i++) E[i] show( )(; }

STORAGE CLASSES
Storage class decides the following 1. Default value 2. life (persistence) 3. scope (accessibility) storage default 1.auto garbage (automatic) 2. static 3. register 4. global Zero garbage zero li ti scope limited to limited to declaration block their Declaration Block throughout The program same as auto same as auto throughout throughout the program The program Static void display ( ); void main ( ) { display( ); display ( ); display( ); } void display( 0 { static int a; cout <<a<<end1; a++; } o/p o 1 2

Auto Void display ( ); Void main( ) { Display( ); Display ( ); Display ( ); } Void display( ) { Cout <<a<<end1; A++; } o/p 3 garbage values will be generated

STATIC DATA
Static data members with in the class Class data { Int a ; Static int 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) {

0 a

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
<obj-name>. <function-name> Syntax <class-name> : : <function-name> DRAWBACKS OF STATIC FUNCTIONS
1. static f n can never non static data numbers. But reverse is true.

2. constructor & Destructor can never be made or declared as static.

Class student { Int roll; Static int count; Public : Student (int i) { Roll =I; ++arunt; } Static void show( ) { Count<<Roll.X Count << total objects alive = <<count; } Student ( ) { Count; } }; Int student : : count; Void main( ) { Student S(10). P(20), Q(30); Student : : show( ); { Student X(40), Y(50); Student : : show( ); } Student : : show( ); } Student : : show ( ); 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 n-id; Public: Static void init( ) { Id=n-id; } Emp( ) { Cout << enter age, name; Cin >> age >> name; Id=n-id; ++n-id; } Void show( ) { Cout <<age<<name<<id; } Solution :Class Emp { Int hae; Char name[20]; Int id; Static int n-id; Public: Employce (int, char *); Static void init id( ); Void show( ); Static void get next id( );

Employce( ); }; Employa :: int next-id; Employce : : employce (int I, char * j) { Age =I; Strcpy (name if); Id = next=id; } Void employce : : init id( ) { Next-id=1; } Void employce :: show( ) { Cout <<age<< <name << << id<<end1; } Void employce : : get next id( ) { Cout << next object wil be given id= <<next id; } Employce : : employce( ) { Next id; } Void main( ) { Employce : : init id( ); Employce : : get next id( ); { Employce { (25, Rahul); Employce f (30, vipin); e. show( ); f. show( ); empoloyce : : get next id( ); } Emloyce : : get next id( ); }

THIS POINTER
Class Emp { Int age; Char name[20]; Float sal; Public : Void get( ) { Cout << enter age, name & sal: Cin >> age>> name>>sal; Cout << Add of calling object = this; } Void show( ) { Cout <<age<<name<<sal; Cout << Add of calling object= <<this; } } Void main( ) { Emp E, f; e.get( ); f.get( ); e.show( ); f.show( ); }
1. Every member f n of class has this pointer.

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

This Pointer

This is a special pointer available in every member foundation of a class except static member f n of a class. Whenever the object of a class puts a call to any non static member f n of that class, the this pointer available in that member f n implicitly starts pointing to the address of calling object. Thus we can say that a this pointer always points or referr to the aurrent object. By default class has 3 this pointer. Constructor copy constructor Destructor Accessing Data Member Using this Class Box { Int l, b, h; Public: Box( ); Box (int, int, int( ); Box (Box &); Void show( ); }; Box : : Box( ) { Cout << Enter l, b, and h; Cin >> l >> b >> h; } Box : : Box (int I, int j, int k) { L=I; thisl=I; B=j; thisb=j; H=k; thish=k; } Box : ; Box (Box &p) { L=p.l; *this=p; B=p.b; H=p.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
This pointer always points to calling object thus it can not incremented or decremented. It is a constant pointer. Box = *q; Q = this+1 valid Q=++this notvalid USING THE CONST KEYWORD 1. 2. 3. 4. Const variable pointer parameters C data members of class 5. member f n of a class

C++

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++ X not valid.

Const Pointer Const int *p => pis a pointer a const int void main( ) { Int b=50; Int a =10; Const int *p; or int const *p P= &a; *p=20 P=*b; } This pointer comes in this category Int * const P P is a const pointer to an integer means P cant be incremented or decremented. Selin they are initialized at the time of declaration. Void main( ) { Int b=50; Int a=10; Int * const P=&a; *p=20; P=&b Const parameter Int strlen (const char * p) { Int I; For (i=0; *(p+i); i++) *p= A X // value of parameter can not be changed } Box (const Box &p) // prototype of default copy constructor { L=p.l ++;

B=p.b H=p.h } Const data members of class Class circle { Int rad; Const flaot pi X; // const var are initialized at the point of declaration thus this is not valid statement Circle (int r) : pie (3.14), rad(r) Initialiser Const Member Function:If we want that a f n do not change value of class member than we make them const. Class circle { Int r; Float a; Void get (int x) { R=x; } Void cal-area ( ) { A=r * r * r * 3.14; } Void show ( ) const { Count << Rad= <<r++ << Area= <<a; } If const is there then value of r will not be changed other wise at last it will be incremented.

INITIALISES
Inialises 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 (s,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); Else if (x>y) Return (1); Else Return (+) } Void main( ) { Box B1, B2; B1. get( ); B2. get( ); B1. show( ); B2. show( ); Int ans ; And = B1. compare (&B2);

if (and= =0) cout << equal; else if (ans >=1) cout << B1 is greater; else cout << B2 is greater }

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 and; Ans=B1. compare (B2); If (ans= =0) Cout << equal; else if (ans >1) cout << B1 is greater; else cout << B2 is greater; }

FRIEND FUNCTIONS
A friend function is a special function which despite of not being member f n of class has full access to the private, protected members of the class.

ATTRIBUTES OF FRIEND FUNCTIONS


1. If a fn is to be made friend of a class then it has to be declared

within the body of the class preceded with the keyword friend.

2. whenever a friend f n is defined neither, the name of class nor scope

resolution operator appears in its definition. Moreour the keyword friend also does not appear. 3. whenever a friend fn is called, neither the name of the object nor dot operator appears toward its left. It may however accept the object as a parameter whose members it wants to access. 4. It does not matter in which diction of class we declare a friend function as we can always access it from any portion of program 5. If a friend fn want to manipulate the values of data members of an object it veds the reference of object to be passed as parameter Example:- // Demonstrating the use of friend function Class student { Int roll; Char grade; Float per; Public: Void get( ); Friend void show (student); }; Void student : : get( ) { Cout << enter roll. Grade & per; Cin >> roll>> grade>>per; } Void show (student P) { Cout << p.roll<< << P.grade<< <<P.per; } Void main( ) { Student S; S. get( ); Show(S); } Demonstrating the use of friend function

Class student { Int roll; Char grade; Float per; Public: Friend void get (student &); Void show( ); }; Void get (student & P) { Cout << enter roll, grade & per; Cin >> P.roll >> P.grade >> P.per; } Void student : : show( ) { Cout << roll << grade << per; } Void main( ) { Student S; Void get(S); s. show( ); } Class student { Int roll; Char grade; Float per; Public: Friend void get (student *P); Void show( ); }; Void get (student *q) { Cout << enter roll, grade & per; Cin >>q roll >> q grade >> q per; } Void student : : show ( )

{ Cout << roll << grade << per; } Void main( ) { Student s; Get (&s0; s.show( ); } A FUNCTION BEING FRIEND OF TWO CLASSES Class Beta; // forward declaration Class Alpha { Int x; Public: Void get( ) { Cout << enter x=; Cin >> x; } Friend void compare (Alpha, Beta); }; Class Beta { Int y; Public: Void set( ) { Cout << enter y=; Cin >>y; } Friend void compare (Alpha, Beta); } Void compare (Alpha A, Beta B) { If (A, X > B. Y) Cout << greater= << A, X;

Else if (B.Y> A.X) Cout << Greater= << B.Y; Else Cout << equal; } Void main( ) { Alpha Obj1; Beta Obj2; Obj1. get( ); Obj2. set( ); Compare (obj1, obj2); }
ADDING TWO OBJECTS OF A CLASS USING MEMEBR FUCNTIONS

Class Distance { Int feet; Int in cher; Public: Void get( ) { Cout << enter feet & inches; Cin >> feet >> inches; } Distance add (Distance &) Void show( ) { Cout << feet= << feet<< inches= <<inches; } }; Distance Distance : : add (Distance &P) { Distance temp; Temp. feet = feet +P. feet; Temp.inches= inches + P.inches; If (temp. inches>=12) { temp. feer += temp. inches/12;

temp. inches % =12 } Return (temp); } Void main( ) { Distance D1, D2, D3; D1. get( ); D2, get( ); D3 = D1. add (d2); D3. show( ); } Class Distance { Int feet, inches; Public: Void get( 0 { // same as previous } Void add (distance &, distance &); Void show( ) { // same as previous; } }; Void distance : : add (distance &d1, distance &d2) { Feet = d1. feet + d2, feet; Inches = d1. inches + d2, inches If (inches >12) { Feet = feet + inches /12; Inches % = 12; } } Void main( ) { Distance d1, d2, d3; d1.get( );, d2.get( );

D3, add (d1, d2); D3. show( ); }

ADDING TWO AF CLASS UISNG PRIED FUNCTION Class distance { Int feet; Int inches; Public: Void get( ) { Void << enter feet & inches; Cin >>feet >> inches; } Void show( ) { //same } Friend distance add (distance, distance ): }; Distance add (Distance P, Distance Q) { Distance temp; Temp. feet = P.feet +Q.ffet; Temp. inches= P.inches + Q.inches; If (temp. inches>=12) { Temp.feet += temp. inches/12; Temp. inches % = 12; } Return (temp); } Void main( ) { Distance D1, D2, D3; D1.get( );

D2.get( ); D3 = add (D1, D2) D3.show( ); }

OPERATOR OVERLOADING
It is a mechanism using which a programmer can make built in operator of C++ act on objects of user defined classes much in the same way like they act on variables of primitive data type. Thus we can say by using operator overloading a programmer can enhance the working range of built in operator from primitive type to non primitive type also. The major advantage offered by operator overloading is the simplicity in readability of the call i.e. f n call which are given using operator overloading are much more easy to interpret as compared to conventional function calls. Operator Overloading can be done 1. Making use of member function 2. making use of friend function. Syntax:<ret-type> operator <op-symbol> (arguments); Friend (ret-type> operator <op-symbol> (<arguments>); Overloading Of Unary Operator As Member Function Of The Class (Pre Increment) Class counter { Int count; Public: Counter( ) { Count =0; } Counter (int c)

{ Count = c } Void operator ++( ); Void show( ) { Cout << count <<end1; } }; Void counter : : operator ++ ( ) { ++ count; } Void main( ) { Counter a = 10; // Single parameterize constractor a.show( ); ++ a; // a. operator + +( ); a. show( ); } Class counter { Int count; Public: Counter( ) { Count = 0; } Counter (int c) { Count = c; } Counter operator ++ ( ); Void show( ) { Cout << count; } }; Counter &

Or Counter counter : : operator ++ ( ) { Counter temp; ++ count; or Temp. count = count; ++ count Return (temp); return (* this); } Void main( ) { Counter c1 = 10, c2; C1. show( ); C2 = ++ c1; C1. show( ); C2. show ( ); } Overloading Of Post Increment Operator Using Member Function Of this class Class counter { Int count; Public: Counter( ) { Count=0; } Counter (int C) { Count = c; } Counter operator ++ (int); Void show( ) { Cout << count; } }; Counter counter : : operator ++ (int) {

Counter temp; Temp. count = count++; Return (temp); } Void main( ) { Coun 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); } Void main ( ) Or counter temp; temp. count = c.count++; return (temp);

{ Counter C1 = 10, C2; C1. show ( ); 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; } Count (int i) { Count = I; { Void show( ) { Cout << count << end1; } }; Void main( ) counter & operator ++(counter &c) { { Counter c1 =10, c2; counter temp; C1. show( 0; temp. count = C, count; C2= ++ C1; C1. show( ); return (temp); C2. show( ); } } Overloading Binary Operators As Member Functions Of The Class

D3 = D1 + D2; D3 = D1. operator + (D2); Class Distance { Int feet, inches; Public: Void get( ) { Count << enter feet and inches; Cin >> feet >> inches; } Void show( ) { Cout << feet << inches; } Distance operator + (Distance); }; Distance Disttacne : : operator + (Distance P) { Distance t; t.feet = feet + P. feet t. inches = inches + P. inches; if (t.inches>= /12) { t.feet + = t.inches/12; t.inches % = 12; } Return (t); } Void main ( ) { Distance D1, D2, D3; D1, get( ); D2, get( ); D3 = D1+D2; D3. show( ); Getch( ); }

Overloading Binary Operator Using Friend Function Class Distance { Int feet, inches; Public: Void get( ) { Cout << enter feet and inches: Cin >> feet>> inches; } Void show( ) { Cout << feet<< inches; } Friend Distance operator + (Distance, Distance); }; Distance Operator + (Distance p, Distance Q) { Distance t; t.feet = P.feet +Q.feet; t.inches = P.inches+ Q.inches; if (t. feet>=12) { t.feet = t.feet +t.inches/12; t.inches % = 12; } Return (t); } Void main ( ) { Distance D1, D2, D3; D1.get( ); D2.get( ); D3=D1+d2; D3.show( ); } Assignment:D2 = D1+n

D3 = n + D1 Class Distance { Int feet, inches; Public: Void get( ) { // same as previous } Void show( ) { // same as previous } Distance Distance : : operator + (int n) { Distance temp; Temp feet = feet + n; Temp. inches = inches + n; If (temp. inches > = 12) { Temp. feet + = temp. inches / 12; Temp. inches % = 12; } Return (temp); } Distance operator + (int P, Distance Q) { Distance temp; Temp.feet = P+Q.feet; Temp. inches= P+Q. inches; If (temp. inches> = 12) { Temp.feet = temp. feet + temp. inches/12; Temp. inches % = 12; } Return (temp); } Void main( ) {

Distance D1, D2, D3; Int n; Cout << enter an integer; Cin >> n; D1. get ( ); I D2 = D1+n; // can be done using member fn & friend fn D2. show( ); Cout << Enter an integer; Cin >>n; D3 = n+D1; // not possible through member fn D3. show( );

II }

Note:II can not be done using member function becoz n is an integer and only an object can call function not integer. So I call can be made using member function as well as friend function but II can be done only friend function Assignment :D1+=D2 using member fn & friend fn

Overloading Relational Operators If (D1= = D2) Compiler if (D1.operator = = (D2) ) Class Distance { Int feet, inches; Public: Void get( ) { Cout << enter feet & inches; Cin >> feet >> inches; } Void show( ) { Cout << feet << << inches; }

Int operator = = (distance D); }; Int Distance : : operator = = (Distance D) { Int x, y; X= feet &12 + inches; Y = D. feet *12 + D.inches; If (x= = y) Return (1); Else Return (0); } Void main( 0 { Distance D1, D2; D1. get( ); D2. get( ); D1. show( ); D2.show( ); If (D1= = D2) Cout << equal; Else Cout << not equal; } Assignment:Modify the above program so that now your cosle prents either of there message i. Object are equal. ii. Dl is greater. iii. D2 is greater Use minimum possible operator Overloading Binary Operator On String Class string { Char str[20]; Public:

String ( ) { Str[0] = \0; } String (char *P); { Strcpy (str, P); } Void show( ) { Cout << str; } String operator + (string S) }; String string : : operator + (string S) { String t; Int I, j; For (i=0; str[i]; i++) t.str[i] = str[i]; for (j=0; s.str[j]; i++, j++) t.str[i] = s.str[j]; return (t); } Void main( ) { String s1= Hello; String s2 = How are you ?; String s3; S3 = s1 +s2; S1. show( ), s2. show( ); }

s3. show( );

Assignment :WAP which compares two string objects & checks which one is greater. Operators Which Can Not Be Overloaded
1>

.(dot operator) member access operator (already overloaded)

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

DYNAMIC MEMORY ALLOCATION (DMA)


MALLOC 1. It is a function 2. Necessary to include the header file 3. It takes no, of bytes as parameter 4. brings memory from local heap 5. Maximum memory that malloc can allocate = 64KB 6. Malloc retirens the address of Allocate block in from of (void*) Thus its return value has to be type Casted accordingly 7. when malloc fails it returns null 8. Malloc only creates a new block But not call the constructor of the Class for initialized the data member Of that block Such 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. when new fails it returns zero on the other hand operator new can allocate memory as well as call the class for initializing the members of block created. Constructors are called dynamic Constructors. Syntax for new;(i) (ii) new <data type> new <data-type> [int];

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

2000 P 2. int &P; P=new int [10]; Delete [ ] P; 3000 P Syntax for deletes .. 3000 2000

10 2002

Here value 10 denotes that programmer is interested in creating memory for elements

1. Delete <ptr-name>; // deletes one block of data type 2. Delete [ ] <ptr-name>; // deletes whole allocated memory Eg:- float *P; Delete P; // four bytes free

Delete is a request to OS it does not work immediately where as new creates memory immediately WAP which creates a dynamic array of user defined size Accept values from user in that array & then find largest element in that array along with its position. Finally it should display the largest element & delete the array. Void main ( ) {

Int n; Cout << How many integers; Cin >> n; Int *P; P+ new int [n]; If (P= = 0) { Cout << Insufficient memory; Getch( ); Exit(1); } For (int i=0; i<n; i++) { Cout << enter element; Cin >> * (p=i); } Int max = *p; Int pos = 0; For (i=1; i<n; i++) { If (* (p+i) > max) { Max = * (p+i); Pos = I; } } Cout << largest element= << max; Cout << Position = << pos; Getch( ); Delete [ ] P; } WAP to create a class c/a string having a character pointer P. provide constructor in the class which accept int as parameter and allocates dynamic array of characters of special size. Now provide following member fn in the class. 1. get string which prompts users to enter string in dynamic array. 2. show string which display the string 3. Reverse string which accept an object as parameter and copies the

Reverse of string stored in calling object in object Passed as parameter. Class string { Char *p; Public : String (int); String ( ); Void show str( ); Void reverse str ( str &); Void get str( ); }; String : : string (int size) { P = new char [size +1]; If (P= =0) Exit (1); N = size +1; } Void string : : get str( ) { Cout << enter string; Cin. Getline (P,n); } Void string : : reverse str (string &s) { Int I, j; For (i=0, j=strlen (p)-1; j>=0; j--, i++) { s.p[i] = p[j]; } S. P [i] = \0; } Void string : : show str( ) { Cout << P << end1; }

String : : string ( ) { Delete [ ]P; Cout << Array destroyed; } Void main ( ) { Int n; Cout << How may character; Cin >> n String S1 =n; String S2 =n; S1. getstr ( ); S1. reverse str(S2); S1. show str( ); S2. show str( ); }

DYNAMIC OBJECTS
Allocating memory for class with the help of new. Class Emp { Int age; Char name[20]; Float sal; Public: Void get( ) { Cout << enter age, name & sal; Cin >> age >> name >> sal; } Void show( ) { Cout << age << << name<< <<sal; } }; Void main( ) {

Emp *P; P=new emp; If (p= =0) { Cout << Memory Insufficient; Exit (1); } p get( ); p show( ); getch ( ); delete p; }

age name sal

ARRAY OF DYNAMIC OBJECTS


Modify the previous code so that now your program creates an array of a objects where n is given by user. Then it should accept values for each object and finally display them. Class Emp { Int age; Char anem[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; New Emp [n]; If ( p = =0) { Cout << error in crating objects; Exit (1); } For (i=0; i<n; i++) (p+i) get( ); or p[i]. get( ); For (i=0; i<n; i++) (p+i) show( ); or p[i]. show( ); Getch( ); Delete[ ]p; } Enhance the above program so that after accepting records of n employees. Your program prompts the user to enter another name & display the record of that employee only. If employee name is not available then program should display the message record not found. Class Emp { Int age; Char name [20]; Float sal; Public: Void get( ) { Cout << enter age, name and sal; Cin >> age>> name>> sal; } Void show( ) { Cout << age<< name << sal; }

Int compare (char *); }; Void main ( ) { Emp *p; Int n; Cout << how many employees?; Cin >> n; P= new emp [n]; If (p = =0) { Cout << Insufficient Memory; Exit (1); } For (i=0; i<n; i++0 (p+i) get( ); or p[i]. get( ); Cout << enter name to search; Char str [20]; Cin. I gnore( ); Cin. Get line (str, 20); For (i=0; i<n; i++0 { If ( (p+i) compare (str) = = 0) { (p+i) show ( ); Break; } } If (I = = n) Cout << Record not found; Getch ( ); Delete [ ] p; } Int compare (char *p) { Return (strcmp ( name.p) ); } Assignment

WAP which creates an array of n objects. Accept values from user in then & display them Now sort the records on the basic of name in ascending order & again display the sorted record Class age; { 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; } Void sort (int); }; Void Emp : : sort (int r) { Int j, I, t; Char temp [20]; For (i=0; i<r; i++) { For (j=i+1; j<r; j++) { If (str cmp( (this +i) name, (this +j) name)>0) { Strcpy (temp, (this +i) name); Strcpy ((this +i) name, (this+jname); Strcpy ((this+j)naem, temp); T=(this+i) age; (this +i) age = t; T= (this+i) sal; (this +i)sal (this+j)sal; or Emp F; *(this+i) =* (this+j); *(this+j) = F;

(this+j) sal=t; } //closing of it } // inner for } /outer for } // closing of function

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( 0 { 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. Terms Used For Dynamic Objects Live Object :- Those object which are initialized using constructor are constructor are c/o live objects. Partially live objects

INHERITANCE
1. Single Inheritance A Base class 2. Multi level Inheritance A indirect base class of C

Derived class

B c

base class of C

3. Multiple Inheritance A B

4. Hierarchial Inheritance A

5. Hybrid Inheritance or Multipath Inheritance A B C

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( 0 { Cout << enter l, band; Cin >> l>>b>>h; } Void show( ) { Cout <<l<< << b<< << h; Base class

} }; Class carton : public Box { Char type[20]; Public: Void set( ) { Cout << enter material name; Cin. Get line (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 becomes 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 becomes 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 The major benefit of early binding is speed of execution i.e. function calls which are bound using early binding get executed at a fastest speed as compared to late binding fn calls. OVERRIING The function overriding is a term which is used when a derive class contains a function with the same prototype as its bass class. In other words, fn provided by base class has same prototype in derive class but in different body. Overriding Scope must be different By the classes related by Inheritance Prototype of functions Must be same . Overloading always in same class means at single level prototype must be different

When Mode Of Inheritance Is Protected When base class is inheritance in protected mode then:-

1. All public members of base class becomes protected member of derive class i.e. they can be accessed only through function of derived class but not by object of derive class. 2. All protected members of base class become protected members of derive class i.e. they two can only be accessed through functions of derived class but not by object of derive class. 3. All private members of base class remains private to their own class & thus neither accessible through the object nor through functions of derive class. Class Num { Protected: Int a, b; Public: Void get( ) { Cout << enter two numbers; Cin >> a >> b; } Void show( ) { Cout << Numbers are =; Cout <<a << << b; } }; Class Add Num : : protected Num { Protected : Int c; Public: Void set( ) { Get( ); } Void add( ) { C=a+b; }

Void display( ) { Show( ); Cout << sum= <<c; } }; Void main ( ) { Add Num obj; Obj. set( ); Obj/./ add( ); Obj. display( ); }

PRIVATE MODE OF INHERITANCE


When a base class is inheritance in private mode then:1. All the public members of base class become private members of

derive class i.e. they can be only accessed through fn of derive class but not by the objects of derive class. 2. All the protected members of base become private members of derive class i.e. they two can only be accessed through the function of derive class but not by objects of derive class. 3. All private members of base class remain private to their own class & thus can neither be accessed by fn nor by objects of derives class. Class Num { Protected : Int a, b; Public: Void get( ) { Cout << enter a and b; Cin >> a >> b; } Void show( ) { Cout << a = <<a<<end1;

Cout << b= << b<< end1; } }; Class Add Num: Private Num { Protected : Int c; Public: Void set( ) { Get( ); } Void add( ) { C=a+b; } Void display ( ) { Show( ); Cout << same = <<c; } }; Void main( ) { Add Num obj; Obj.set( ); Obj. add( ); Obj. display( ); } Note:- At single level Inheritance private & protected inheritance seems to be similar.

MULTILEVEL INHERITANCE
Class Num { Protected: Int a, b;

Public: Void get( ) { Cout << enter a nad b: Cin >> a >> b; } Void show( ) { Cout << a= <<a<<end1; Cout << b= <<b<<end1; } }; Class Add-Num : public Num { Protected : Int c; Public : Void set( ) { Get( ); } Void display( ) { Show( ); Cout << sum= <<c; } Void add( ) { C=a+b; } }; Class Diff Num : public Add Num { Int d; Public: Void accept( ) { Set( ); }

Void diff( ) { D= a b; } Void print( ) { Display ( ); Cout << Difference= <<d; } }; Void main( ) { Diff Num obj; Obj. accept( ); Obj. add( ); Obj. diff( ); Obj. print( ); } Program Class counter { Protected: Int count; Public: Void init (int a) { Count =a; } Void operator ++( ) { Count ++; } Void show( ) { Cout << count= <<count; } }; Class Dec Counter : public counter

{ Public: Void operator - -( ) { - - count; } }; Void main( ) { Dec counter 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) (ii) (iii) (iv) (v) input display sort in ascending sort in descending quit

Solution #include <iostream.h> #include <stdlib.h> Class Array { Protected:

Int a[10]; 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 : : arcsort ( ) { 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] = j; } } } }

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): Case (5): Exit(1) } } while (ch !=5) Getch( ); } Sr.ascsort( ); Break; sr.descsort( ); Break;

MULTIPLE INHERITANCE
Class Base 1 { 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+d; } Void print( ) { Show( ); Display( ); Cout << sem = <<c; } }; Void main( ) { Drv obj; Obj. accept( ); Obj. add( 0; 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 Base 2 { Protected: Int b; Public: Void set( 0 { 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( );

Role Of Constructor & Destructor In Inheritance As a basic rule in inheritance, it a base class contains a constructor and destructor as well as derive class also contains constructor & destructor, then when object of derive class is created, constructor of base class gets executed first followed by constructor of derive class and the destructor is called in reverse order i.e. the destructor of derive class is called first followed by the destructor of base class. Thus we can say constructor are always called in the order of inheritance and destructor are called in reverse order. Class Base { Public : Base ( ) { Cout << In bases constructor <<end1; } Base( 0 { Cout << In bases destructor <<end1; } };

Class drv: public name { Public: Drv( ) { Cout << In derives const <<end1; } Drv( ) { Cout << In derives destructor <<end1: } }; Void main( ) { { Drv obj; } Getch( ); } Class Base { Protected a, b; Public: Base (int I, int j) { A = I; B = j; } Void show( ) { Cout << a << << b; } }; Class drv : public base { Int c; Public: Drv ( ): base (10, 20)

{ C=a+b; } Void show( ) { Base : : show( ); Cout << sum = << c; } }; Void main( ) { Drv obj1 Drv obj2 Obj1. show( ); Obj2. show( ); } Constructor Calling In Multiple Inheritance Base 1 Int a; Base1 (int); Void show( ); base2 int b; base2 (int); void display rv nt c;

Class Base1 { Protected: Int a; Public: Base (int i) { A = I; } Void show( ) { Cout << a; } };

Class Base2 { Protected : Int a; 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) : base 1 (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) derive class must have constructor Base class constructor should be called in derives constructor.

Constructor Calling In Multilevel Inheritance Class Base1 { Protected: Int a ; Public: Base 1(int i) { A=1; } Void show( ) { Cout << a << end1; } }; Class Base2 { Protected: Int b; Public: Base2 (int I, int j): Base1 (i) { B=j; } Void display( ) { Cout << b << end 1; } }; 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 Add Num : public Num { Int c; Public: Add num (int I, intj) : Num (I, j) { C=a+b; { Void show( ) { Num : : show( ); Cout << sum = <<c; } }; Class Diff num : public Num { Int d; Public : Diff Num (int x, int y) : Num (x, y) { b= a b; } Void show( ) { Num : : show( ); Cout << Difference = << d; } }; Void main( ) { Add Num addobj (10, 20); DiffNUm diffobj (30, 70); Add obj. show( );

Diffobj. Show( ); }

HYBRID INHERITANCE
Class Base { Public: Int a; }; Class drv1 : virtual public base { Public: Int b; }; Class drv2: virtual pubic base { Public: Int c; }; Class drv3 : public drv1, public drv2 { Public: Int d; }; Void main( ) { Drv 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 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.

Internal Working Of Virtual Function Class A { Int a; Public: Void f1( ) { } Virtual void f2( ) obj1 VPTR a { } }; Class B : public A { int x; Public: Void f4( ); Void f2( ); obj2 VPTR }; VTABLE FOR A &A : : f2( ) &A : : f3( 0

VTABLE FOR B &B : : f2( ) &A : f3( )

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

VTABLE:For every class in C++ which contains at least one virtual function a special look up table for storing addresses of there virtual function is created which is known as VTABLE or virtual Table. Thus in short VTABLE is a table containing addresses of virtual functions of the class as well as virtual function of base class if they are not overridden. This table is then consulted by the compiler when a call for virtual function is encountered during runtime. VVPTR:(Virtual Void Pointer) For every class which contains a virtual function special pointer is created by the compiler known as VVPTR, which is used for pointing to the virtual table. Thus every object of class containing virtual function has its size incremented by2. Now whenever compiler encounters call for virtual function through a pointer, it first refers to the address of object to which pointer is pointing from their it reads the address contained in VVPTR of the object the which is the address of VTABLE of class. Lastly within the VATBLE it executes the virtual function called. Thus virtual function enhances the size of code as reduces the execution speed but provides a flexible way of designing program which can respond to the changes which accur at run time. Class Data { Int a ; Data (int ); Public: Static Data get Objects( ); Void show( ); }; Data : : Data (int i) { A = I; } Data Data : : get object( ) { Data D (10); Return (D); } Void Data : : show( )

{ Cout << a; } Void main( ) { Data D = Data. Get object( ); 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 1. Function Overloading 2. Operator Overloading 3. Early Binding Virtual Inheritance Run Time Polymorphism 1. Function Overriding 2. Virtual Function 3. Late Binding avoids multiple copies Polymorphism (converts parly binding to late binding) Class Figure { Protected: Int dim1, dim2; Public : Void get( ) { Cout << enter 1st & 2nd dimension; Cin >> dim1>> dim2; } }; Class Rectangle : public Figure { Public:

Void area( ) { Cout << area of Rectangle=; Cout << dim1 * dim2; } }; Class Triangle : public Figure { Public: Void area( ) { Cout << area = <<5 * dim1 *dim2; } }; Void main( ) { Figure *p; Figure F; P = &F; p get( 0; p area( ); rectangle R; p=&R; p get( ); p area( ); triangle T; p = & T; p get( ); p area( ); }

PURE VIRTAUL FUNCTIONS


Def:- If a virtual functions declarations is equated with zero then it is known as pure virtual fn. In other words, it we do not want to provide any definition for a virtual fn wee can equate with zero then it will be known as

pure virtual fn. Thus by definition a pure virtual fn is one which has no body define with in its own class or base class.

ABSTRACT CLASS
1. If a class contain at least one pure virtual fn than it is known as

abstract Base class. 2. we can never create any object of abstract class but we can always create its pointers. This is because whenever an object of a class containing virtual function is created a VTABLE is setup by the complete, which stores the address of virtual function has no body it can not have memory address & thus it can not places in VTABLE. So to prevent any accidental calls to a non-existing pure virtual function compiler prohibits the creation of an object of an abstract class. 3. An class which extends an Abstract Base class must provide its own definition of pure virtual fn available in its base class other wise the class itself would be created as an abstract class & then it too can not be instantiated. Note:- Constructors can not be virtual since link between VPTR VTABLE is made by constructor Virtual Destructor:Class Base { Protected: Public: Int *p; base( ) { P=new int [10]; Cout << p constructed!; } base { Delete [ ] p; Cout << memory deallocated; }

Virtual

}; Class drv : public Base { Int *q; Public : Drv( ) { Q = new int [10]; Cout << q constructed; } Drv( ) { Delete [ ] q; Cout << memory deallocated for q; } }; Void main( ) { Base *ptr; Ptr = new drv; Delete ptr; } Destructor can not be declared as pure virtual. Since it is not possible to leave empty body of destructor since at the time of call of destructor same activity must be performed.

FILE HANDLING (STREAM I/O)


Flow of data If flow of data is from program towards device then o/p stream eg. Cout . is used. If flow of data is from device to program then i/p stream eg cin is used. Monitor / Buffer Monitor

Input stream C++ Program Input stream

output stream

output stream

Hard-disk Classes Available In C++ For File Handling 1. Of Stream:2. It Stream:3. Fstream :-

Hard disk

If a class whose objects can be created for writing data to secondary memory of file. is a class whose objects can be created for reading data from file. whose object can read / write the data in a file.

Steap Required For Writing Data In File Step 1 Create the object of Of stream class Eg:- Of stream obj; Step 2 Connect the object with file on your system. Step 3 write the data through the object in file. Step 4 Close the file. C++ Implement Of Above Steps Step 1 Step 2 Step 3 Step 4 (a) (a) (b) Of stream obj; obj. Open ( Data. Txt); obj << Hello; obj. put (H); obj.close ( );

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

2(a) Of stream obj; Bj.open (Data. Txt,

clas ios : : app)

static data File Opening Mode

3 Of stream obj ( Data. Txt, ios : : app) Step For Creating A Program For Reading A File 1. Create the object of ifstream class. 2. Connect the object with the file on your system & check whether file is available or not. 3. Read the data through object from file. 4. class file. C++ IMPLEMENTATION 1. If stream obj 2. (a) Obj. Open ( Data.txt); Or If stream obj; Obj.open ( Data. Txt, ios : : in); Or If stream obj (Data.txt, ios: : in); Creating Object Of fstream Class 1. fstream obj; Obj.open ( Data.text, ios : : out | ios : : in); 2. Using Constructor Fstream obj ( Data.txt, ios : : out | ios : : in); WAP to create a file c/a message. text Accept a line of text from user & write it in file character by character #include <stdlib.h> #include <iostream.h> #include <fstream.h> #include <conio.h> Void main ( )

{ Of stream out ( Message. Text); If (!out) { Cout << file can not be opened; Getch ( ); Exit(1); } Char str[80]; Cout << enter a line of text; Cin.qetline (str, 80); Int i=0; While (str[i]) { Out.put (str[i]); I++; } Cout << file written successfully; Getch ( ); Out. Close( ); } 1 Note:isopen ( ) 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); Retruns I if not connected Returns 1 if conceted

} Char ch; While (! In.enf( ) ) { Ch=in.get( ); Cout << ch; } Getch( ); In.close( ); } Que:- WAP to open a file c/a Data.txt. Accept a line of text from user & write it on file character by character basic and it in the same program read file and print its content on the screen . Void main( ) { Fstream Nisha ( Data, ios: : out | ios: : in); If (! Nisha) { Cout << error opening file; Exit(1); } Char str [80]; Cout << enter a line of text; Cin.get line (str, 80); Int i=0; Char ch; While (str [i]) { Ch=str[i]; Obj.put (ch); I++; } Obj.seekg (0); While (! Obj.eof( ) ) { Ch=obj.get( ); Cout << ch; }

Getch( ); Obj. close( ); } Que Assume there is a file c/a Message. Txt containing certain line of txt. Create a file c/a Message2.txt, and copy the contents of messages.txt into it. Before coping the character must be converted upper to lower & vice versa & spaces must be skipper. Finally display the contents of Message2 txt. Void main( ) { If stream obj1 ( Messages.txt); Stream obj2 (Message2. txt, ios : : out | ios : : in); Char ch; If (! Obj1) { Cout << sourcl file cant be opened; Exit(1); } While (! Obj1, eof) { Ch = obj1. get( ); If (ch! = 32) { If (ch>=65 & & ch<=90) Ch=ch+32; Else if (ch > =97 && ch <=122) Ch=ch-32; } Obj2.put(ch); } Obj2.seekg(0); While ( ! obj2. eof( ) ) { Ch=obj2. get( ); Cout << ch; } Getch( ); Obj2.closs( );

Obj1. close( ); } READING AND WRITING STRINGS Void main ( ) { Fstream obj ( Data.txt, ios : : out | ios : : in); If !(!obj) { Cout << error; Exit (1); } Char text [80]; Cout << how many lines; Int n; Cin >> n; Cout << Enter << n<< lines each terminated by enter : <<end1; For (in i=1; i<=n; i++) { Cin.get line (text, 80); Obj << text << end1; } Obj. seekg (0); Cout << File written press nay key to read; Gecth( 0; While (!obj.eof( ) ) { Obj.getline (text,80); Cout << text << end1; } Gecth( ); Obj.close( ); } Void main( ) { Fstream obj ( Data.txt, ios : : out | ios : : in); If (!obj) { Cout << error;

Exit(1); } Char text [80]; Cout << enter lines and press enter on new line to stop; While (1) { Cin.getline (text, 80); If (strlen (text) = =0) Break; Obj << text << end1; } } FILE OPENING MODES 1. ios : : out (Default mode of ofstream) If file is not existing then it is created. Otherwise data gets Erased and pointer is placed at the beginning. If file is existing, pointer is placed a the beginning otherwise error is generated. 3. ios : : app It can not alter previous contents but can add new content at the End of file. 4. ios : : ate (ate stands for at the end) Allows updations as well as adding of new data. In this pointer can move forward and backward.

2. ios : : in

5. ios : : trunc Needed only in fstream. Used with ios : : out Truncate previous data & brings pointer to beginning. 6. ios : : nerplace Used with ios : : out if file is existing do not replace it otherwise create it. 7. ios : : nocreate

Used with ios : : out if file is existing overwrite it otherwise do not create it. 8. ios : : binary If we want to write data in binary form.

BINARY I /O
Void write 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 On successfully reading from file it returns 1 on error it return 0. Reading and writing class objects Class Emp { Int age; Char name [20]; Float sal; Public: Void get( ) {

Cout << enter age, name and sal; Cin >> age >> name>> sal; } Void show( ) { Cout << age << } }; Void main ( ) { Emp E; Fstream obj ( Records.dat, ios : : out | ios : : in | ios : : trunc| ios : : Binary ); If (! Obj) { Cout << error in opening file; Exit (1); } E.get( ); Obj.write ((char *) &E, size of (Emp) ); Obj.seekg(0); Emp F; Obj.read ((char *) &F, size of (Emp)); F.show( ); Getch( ); Obj.close( ); } Reading And Writing Multiple Objects Void main ( ) { Emp E; Fstream obj ( Record.dat, ios: : out| ios : : in | ios : : trunc | ios : : Binary); If (! Obj) { Out << error in opening file; Exit (1);

<<name << sal <<end1;

} Char choice; { e.get( ); obj.write ((char *) &E, size of (Emp)); cout << Any More (Y/N); cin.ignore( ); cin >> choice; } while ( ch = = y); Obj. seekg (0); While (opj.read (char *) &E, size of (emp)) E.show( ); getch( ); obj.close( ); } Typical Feature Of Read:Note :If in any ane program, we want to read file successively to eof we must clear the flag Obj. seekg (0); Obj. clear( );

Q. WAP to write multiple records of type emp in a file. Accept a name from user & display the record of the employee by searching it with in the file and display the appropriate message Void main( ) { Int flat = 0 Emp E; Fstream obj1 ( Ekta, txt, ios : : out | ios : : in | ios : : trunc | Ios : ; binary); If (! Obj) { Cout << error; Exit(1); } Char ch;

Do { E.get( ); Obj.write ( ( char *) &E, size of (Emp)); Cout << Ant more (y/n); Cin . ignore ( ); } while (ch = = Y); Char name [20]; Cout << enter name to search; Cin >> name; Obj. seekg(0); While (obj.read (char *) &E, size of (emp)) { If ( ! ( E = = name) ) { E. show( ); Flag =1; Break; } } If ( ! flag) or if (flag = =0) { Cout << Record not found; Obj1. close( ); } Int operator = = (char * ptr) { Return (strcmp (name, ptr) ); } } RANDOM I/O Q. Assume there is a file c/a Record.dat which contains several records of type emp. WAP to open this file & read the last record. Void main ( ) {

Ifstream in ( Records.dal, ios : : in | ios : : binary); If ( ! in) { Cout << error; Exit (1); } In.seekg (-1 * size of (emp), ios : : end); Emp E; In. read ( ( char *) &E, size of (emp)); E.show( ); In.close( ); Getch( ); } Note:Prototype of seekg( ) Void seekg (int, int) No, of position of movement Bytes to ios : : beg Move ios : : cur Ios : : end WAP to accept a name from user. Search the record of that employee in Records.dat & Add a new record at its position by accepting it from user Void main( ) { Char temp[20]; Emp E; Fstream in ( Records.dat, ios : : in | ios : : ate| ios : : binary); Cout << enter name to update; Cin >> temp; In.seekg(0); While (in.read ( (char *) &E, size of (emp) ) { If ( ( E = =temp) = =0) { E.get( ); In.seekg (-1 * size of (Emp), ios : : cur); In.write ( ( char *) &E, size of (emp));

Breack; } } In.clear( ); In.seekg(0); While (in.read ( ( char *) &E, size of (Emp) ) E.show( ); Int operator = =(char *n) { Return (strcmp (temp, ptr) ); } } Assignment :1. WAP to delete record given by user from file. 2. WAP to update just the salary of employee whose name given by user.

TEMPLATES
Templates are a technique provide by C++ using which a programmer can define a single function in which last to be carried out is mentioned but the datatype is not mentioned. During runtime by looking at the call of the function & its parameter type the compiler generates specific version of that function to act according to parameter passed. Thus in other words, we can say templates are generic functions which at the time of creation are only told what to do & during run time they become aware on what type of argument it has to be done. Templates are of two type (i) Function Template (ii) Class Template Syntax Function Template

Template <class <type-name> > <return type> < function-name> (< type-name> <arg-name>) Example Template <class T> Void display ( T n) { Cout << n << end1; } Void main ( ) { Int a =10; Char b = x; Float c= 11.5; Display (a); Display (b); Display (c); } Write a function template c/a swap which accepts two parameters & swaps then. Parameters passed can be two integer, two floats two class. Finally two swapped values must be displayed in the function main Template <class T> Void swap ( T &a, T &b) { T temp; Temp = a; A= b; B = temp; } Void main ( ) { Int a, b; Cout << enter two integers; Cin >> a >> b; Swap (a, b); Cout << a= <<a<< b= <<b<<end1; Cout << enter two character;

Char p, q; Cin >> p >>q; Swap (p, q); Cout << p= <<p<<q = <<q <<end1; Float x, y; Cout << enter two float numbers; Cin >> x>>y; Swap (x, y); Cout << x= <<x<< y= <<y << end1; } Q. write a function template which accepts two values as an argument & return maximum amongst then. Template <class T> T greater ( T &P, T 7q) { If ( p > q) Return (p); Else Return (q); } Void main ( ) { Int a, b; Cout << enter two integers:; Cin >> a >> b; Cout << maximum = << greater (a, b); Cout << Enter two charr: Char x, y; Cin >> x >>y; Cout << maximum = << greater (x, y); } Write a function template c/a greatest which accepts an array as an argument & returns the largest element of that array. The array passed can be of different type and different size. Template <class T>

T greatest ( T *a, int n) { Int I; T max = *a; For (i=1; i<n ; i++) { If ( * (a+i) > max) Max = * (a+i); } Return (max); } Void main ( ) { Int arr[ ] = {7, 11, 2, 3, 4, 8}; Float brr[ ] = { 10.4, 11.3, 6.5, 8.2}; Cout << max int = << max (arr, 6); Cout max float= << max (brr, 4); }

CLASS TEMPLATE
Template <class T> Class Data { T a; T b; T c; Public: Void get( ) { Cin >> a >> b; } Void add ( ) { C = a+b; } Void show( )

{ Cout << values are = << a << end1; Cout << b; Cout << sum= <<c; } }; Void main ( ) { Data <int> obj1; Data ,double> bj2; Cout << enter two int; Obj1.add( ); Cout << enter two doubles; Obj1, get( ); Obj2. add( ); Obj1. show( ); Obj2. show( ); } Class Template With Different Generic Type Template <class T1, class T2> Class Data { T1, a; T2, b; Public: Void get( ) { Cin >> a >>b; } Void show( ) { Cout << values are = << a << and << b<< end1; } }; Void main( ) { Data <int, float> obj1;

Data <double, char> obj2; Cout << enter an int and float; Obj1.get( ); Obj1.show( ); Cout << enter double and char; Obj2.get( ) Obj2.show( ); } Q. write a class template for a class called stack and implement three basic operations of stack push, pop and peek. The stack can be of int, char and flots. Template <class> Class stack { T arr [S]; Int tos; Public: Stack ( ) { Tos = -1; } T pop ( ); }; Template <class T> Void stack <T> : : push (T n) { If (tos = = 4) { Cout << stack overflow; Return; } ++ tos Arr [tos] = n; } Template <class T> T stack <T> : : pop ( ) { If (tos = = -1)

{ Cout << stack under floaw; Return(-1) } Return (arr [tos - -]); } Void main ( ) { Stack <int> sa; Int n; Stack <char> s2; Char ch; For (int i=1; i<=6; i++) { Cout << enter int to be pushed; Cin >> n; S1.push(n); } For (int i=1; I,6; i++) Cout << element popped = << s1.pop( ); } Overloading Of Assignment Operator Class string { Char *p; Public: String (int); Void set string (char *); Void resetstrign ( char *); Void display ( ); String( ); }; String : : string (int n) { P=new int [n+1]; } Void string : : setstring (char *str)

{ Strcpy (p, str); } Void string : : resetstring (char *s) { Strcpy (p, s); } Void string : : display ( ) { Cout << p <<end1; } String : : string( ) { Delete [ ] p; Cout << Memory deallocated; } Void main ( ) { String s1 = 20; String s2 = 20; S11. setstring ( Hello User); S2=s1; S1. display ( ); S2. display ( ); S1. resetstring ( Welcome); S1. display ( ); S2. display( ); } Note:when ever the class is containing dynamic pointer then it is necessary to overload assignment operator At the time of overloading = it is necessary to pass parameter by reference. ( eg ( string & s) ). Note :For cascading of assignment operator it is necessary that return type must be string

void string : : operator (string &s) { strcpy 9p, s.p); x=s.x; }

String string : : operator = (string &s) { String (p, s, p); X= s,x; Return (* this); } Note :Q. why do we overload assignment operator? Ans:- The default assignment operator provided by C++ is used for copying one object of class to another but it copies the value bit by bit i.e. the value contained in every bit of source object are copied in every bit of destination object. This behaviour is perfect if source cosle is not containing any pointer to dynamically alloveated block, but if it is so then the default equl to (=) operator will simply copy the address stored in the pointer with in source object to pointer in the destination object. This will make two the defferent pointers point to same location which may cause multiple problems like the destructor calling delete operator for the same memory to overcome this, a programmer should overload the equal (=) operator & provide his own definition for copying the data pointer by pointer of source object rather than address. Overloading Of Insertion And Extraction Operator Prototy Of << operator:Friend ostream & operator << (ostream & cout, strudent &p); Class Emp { Int age; Char name [20]; Float sal; Public: Friend istream & operator >> (istream 7, Emp&); Friend ostream & operator << (ostream &, Emp &); }; Istream & operator >> (istream & in, Emp & p) {

In >> P.age >> P.sal >> P.name; Return (in); } Ostream & operator << (ostream & out, Emp &P) { Out << P.age << << P.name<< << p.sal; Return out; } Void main( ) { Emp E, F; Cout << Enter age, name and sal; Cin >> E; Cout << Enter age, name & sal; Cin >> F; Cout << E << end1; Cout << F <<end1; Q. What is the need of overloading insertion and extraction operator? Ans:- In C++, all primitive types like int, float, char etc. are display on console using predefined object cout along with insertion operator (<<). Now if programmer wishes to use the same way of displaying objects of his class on screen then he has to overload insertion and extraction operator so that they can be derictly used with user defined objects. Q. Why 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 regular symmetry of insertion operator and so it must be overloaded as friend function. Q. Equal Operator can never be overloaded as friend function. Ans:- Since equal operator should return the reference of calling object (to support coscading). It has to be overloaded as member function as friend function do not have any calling object

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

TYPE CONVERSION
Type conversion is the process using a programmer can convert value from primitive to non primitive and vice versa as well as from one object of class to another object of different class. Thus type conversion falls in three categories:1> Basic to User Defined 2> User Defined to Basic (Primitive ) 3> User Defined to User Defined Conversion Between Basic TO User Defined Constructor (Basic type { // steps to convert basic to user defined } Conversion Between User Defined TO Basic Operator primitive type of C++ ( ) return type { // steps to convert basic to user defined Return (<basic val>); } Example User To Basic & Basic To User Class Meter { Float length; Public : Meter ( ) { Length = 0.0;

} Meter (float cm) { Length = CM/100; } Operator float( ) { Flaot ans= length * 100.0; Return (ans); } Void accept meters( ) { Cout << enter length in (int meters); Cin >> length ; } Void show meter( ) { Cout << In meter = << length ; } }; Void main ( ) { Meter M1 = 250; Meter M2; M2.accept Meter( ); Float cm = m2; // float CM= M2. operator float( ); Cout << 250 Meters when converted; M1. show Meter( ); M2. show Meter( ); Cout when converted to cms = << cm } Program :- Asignment Class String { Char str [10]; Public: String (int n) { Itoa (n, str, 10);

} String( ) { Str [0]= \0; } Operator int( ) { K=1; I= strlen (str); While (i>=0) { Sum = sum + (str [i] -48)* k K * = 10; I - -; } Conversion From User Defined To User Defined 1. Conversion Routine In Source Object:Operator <destination_class-name> ( ) { //routines to convert source to destination Return ( <destination object>); } 2. Conversion Routine In Destination Object:Constructor ( <source class name>) { //routines to convert source to diction } Conversion From User Defined To User Defined By Placing Conversion Routine In Source Object Class Radian { Float rad; Public: Radian ( ) {

Rad = 0.0; } Radian (float r) { Rad = r; } Void show( ) { Cout << Radian = << rad << end1; } }; Class Degree { Float deg; Public: Degree( ) { Beg = 0.0; } Operator Radian ( ) { Float x = deg * PI/180; Radian obj = x; Return (obj ); } Void show( ) { Cout << Degree= << deg; } Void getdagree( ) { Cout << enter angle in degree=; Cin >> deg; } }; Void main ( ) { Degree D; d. getdegree( ); Radian R;

R=D; D. show( ); R. show( ); } Class Degree { Float deg; Public: Degree( ) { Deg =0.0; } Void show( )_ { Cout << Degrees= << deg; } Void getdata( ) { Cout << enter angle in degrees; Cin >> deg; } Flaot getDree( ) { Return (deg); } }; Class Radian { Float rad; Public: Radian (Degree Obj) { Rad = obj.get Dece ( ) * PI/180; } Radian ( ) { Rad=0.0; } Void show( )

{ Cout << Radian + << rad; } }; Void main( ) { Degree D; D.getData( ); Radian R = D; 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( )

// Radian R (D);

{ Cout << in hour = << time; } }; Void main( ) { Hour t1=3600; Hour t2; T2. accept( ); Float x = t2; Cout << 3600 when converted to hours=; T1.show( ); T2.shjow( ); Cout << when converted to sconds = <<x; Getch( ); }

CONSOLE I/O OPERATIONS Unformatted 1. Unformatted I/O (a) istream & get (char &) (b) int get( ) (c) istream & get (char *, int) Example :- cin.get(ch); Can read only characters Cin=cin.get( ); Istream & getline (char *, int num, char delimiter); Istream & getline (char *, int num); Example :Void main ( ) { Formatted can be called by cin

Char ch; Cout << enter text and press enter to stop; Cin. Get (ch); While (ch ! =\n) { Cout << ch; Cin.get(ch); } Getch( ); } Void main ( ) { Char country [20], capital [20]; Cout << enter country name:; Cin.get (country,20); cin.getline (country, 20); Cout << enter capital; Cin.getline (capital, 20); Cout << contry is << country << end1; Cout << its capital = << capital << end1; } Note:cin.getline (country, 20, *)

This will terminate after 19 character or on pressing *, nothing will happen on pressing enter rey. Functions Of Ostream Class (a) ostream & put (char) (b) ostream & write (char *, int) This will start from base add upto no. of integers given. Example :Void main( ) { Char str[ ] = { programming }; Int I; For (i=0; i<strlen (str); i++) { Cout.put (str [i]);

Cout << end1; } For (i=1; i<=strlen(str); i++) { Cout.write (str, i); Cout << end1; } For (i=strlen (str) ; i>=1; i--) { Cout.write (str, i); Cout << end1; } }

FORMATTED I/O
Function (i)width( ) (ii) precision( ) (iii) fill( ) (iv) setf( ) (v) unsetf( ) Description specifies required no of fields to be used for displaying the output. This fn is used for alignment. specifies the no of values to be displayed after decimal pt specifies a character to be used to fill the unused area of field. By default the fulling is done using spaces. sets the format flag to be used while displaying the output. clears the flogs set using setf & restones the default settling.

Defining field Width Prototype:- int width( ) Returns the current width. Int width (int) Old width aurrent width Void main( )

{ Cout. Width(4); Cout << 123; Cout.width(4); Cout. << 39; Cout.width(2); Cout << 2345 } Setting Precision Prototype :-int precision ( ) By default Int precision (int) precision is of 6 pt. Void main ( ) { Cout precision (2); Cout << 2.23 << end1; Cout << 5. 169 << end1; Cout << 4.003 << end1; } Output 2,23 5.17 4 Filling :Int fill( ) Int fill (char) Void main( ) { Cout.file ( *); Cout.precision(2); Cout.width(6); Cout << 12.53; Cout.width(6); Cout << 20.5; Cout. width(6); Cout << 2; }

o/p * 12.53* * * 20.5 * * * * * 2 Note There is no need to set fill and precision again and again while width flag must be set again and again. Formatting With Flags & Bit Fields 1> setf long self (log-setbits, long field) Flag-value (1st argument) Bit field (2nd Arguments Description Ios : : left ios : : adjust field justifies the output on left side. Ios : : right ios : : adjeist field justifies the output in sight align mennes. Ios : : internal ios : : adjust field passing accurs between the sign or base indicator & the value when the value fails to fill the entire width ios : : dec ios : : base field display the data in decimal conversion ios : : oct display the data in actor ios : : hax display the data in hexadecimal ios : : scientific ios : : float field user exponential floating notation ios : : fixed user normal floating notation Example :Void main ( ) { Cout.self (ios : ; left, ios : : adjust field); Cout.fill (*); Cout. precision (2); Cout.width (6); Cout << 12.53; Cout.width (6);

Cout << 20.5; Cout.witdth (6); Cout <<2; } 12.53 * 20.5 * * 2 * * * * * Void main ( ) { Cout.self (ios : : internal | ios : : adjust field ); Cout.field (*); Cout. precision (2); Cout. width (10); Cout << -420.53; } Output : - - * * * 4 2 0 . 5 3 Displaying Trailing Zeros & Plus Sign Long self (long setbits) (i) ios : : show pint (for trailing zeros) (ii) ios : : show pos (for plus sign) void main ( ) { Cout.setf (ios : : show point); Cout.precision (2); Cout << 20.55 << end1; Cout << 55.55 << end1; Cout << 20.40 << end1; } 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 20.55 55.55 20.40

} Output + * 4 2 0 . 5 3 0

Formatting Data Using Manipulators Non Parameterised Manipulators Manipulator 1. end1 2. dec 3. bex 4. oct 5. flush Description

terminates the line and transfers the cursor to next row. set conversion base to 10. set the conversion field to 16. set the conversion field to 8 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 << Its hexadecimal value= << hex<<n; Cout. self (ios : : show base); Cout << a; } Output:- no is = 64 Its hexaslccimal value = 40 0x 40 Example :- void main ( ) { Int n; Cout << enter number; Cin >> nex>> n;

Cout << number= << n; } Parameterised Manipulators Manipulator 1. setw (int) 2. setprecision (int) 3. setfil (char) 4. setbase (int) 5. setiosflag (long) 6. resetiosflag (long) 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.

Example :Void main ( ) { Int n = 100; Cout << hex <<n << << dec <<n << end1; Float f = 122.3434; Cout << f << end1; Cout << setprecision (3); Cout << f << end1; Cout << setiosflag (ios : : internal } ios : : show base); Cout << hex << n << end1; Cout << setiosfloag (ios : : scientifie) << f << end1; } Output:64 100 122.34339 9 122. 343 0x0064 1. 2 2 3 c + 0. 2

Overloading [ ] Operator

Class Array { Int *P; Int n; Public : Array (int size) { P=new int [size]; N=size; } Int & operator [ ] (int i) { Return (* (p+i) ); } Void fil (int pos, int value) { * (p+pos) = value; } Array ( ) { Delete [ ]p; } }; Void main ( ) { Array obj(5); Int x; For (int i=0; i<5; i++) { Cin >> x; Obj.fill (I, x); or obj [i] = x } For (I = 0; i<5; i++) { Cout << obj [i]; } } Overloading Of Operator ( )

Class Box { Int l, b, h; Public: Box operator ( ) (int, int, int); Void get( ) { Cout << enter l, b and h; Cin >> l >> b >> h; } Void show( ) { Cout << l, << << b << << h; } }; Box Box : : Operator (int l, int b, int h) { Box temp; Temp.l = l + this l; Temp.b = b + this b; Temp.h = h + this h; Return (temp); } Void main ( ) { Box B1; B1.get( ); Box B2; B2 = B1 (5, 3, 9); // B2 = B1. operator ( ) (5, 3, 9); B1. show( ); B2. show( 0; }

GRAPHICS MODE PROGRAMMING


Steps Required For Designing Graphics Mode Program

1> Concert the display monitor from text mode to graphics mode. 2> Perform the required graphics operation like filling coloring, drawing etc. 3> Finally close the graphics mode and restore character mode. Converting Character To Pixels 1. void init gragraph (int *, int *, char *) Driver resolution path of BGI file Or Mode 2. Drawing using built in functions. 3. void close graph( ); Void restorecrtmode( ); Program:- WAP to couvert monitor display mode from char to pixel and print welcome message. #include <graphics.h> #include <conio.h> #include <stdlib.h> Void main( ) { Int gd, gm, ec; Gd= DETECT; Inttgraph (&gd, &gm, C:\\TC\\BGI); Ec= graphresult( ); If (ec!=grOk) or (ec!=0) { Printf (error in initialising); Exit(1); } Cleardevice Outtext ( welcome to graphics); Getch( ); Closegraph( ); Restarectmode( ); } Note:-

Int getmaxx( ); Int getmaxy( ):Assignment:-

returns the maximum value of x coordinate. returns the minimum value of if coordinate. Modify the above code so that now code display the Message at the necter of screen.

Void main ( ) { Int gd, gm, ec; Gd = DETECT; Initgraph (&gd, & gm, C:\\TC\\BGI); Ec=graphresult( ); If (ec ! = grOk) { Printf ( error); Exit(1); } Cleardevice( ); Int a = getmaxx( ); Int b = getmaxy( ); Outtextry ( ( a/2), (b/2), welcome to graphics); Getch( ); Closegraph( ); Restorecrtmode( ); } Q. WAP to accept user name & then convert screen to graphics mode & display the name given by user at the center of the screen on char at a time. Void main ( ) { Char str[20] Int gd, gm, ec; Gd = DETECT; Initgraph (&gd, &gm, c:\\TC\\BGI); Ec = graphresult( ); If (ec!=grOk) { Printf ( error); Exit(1);

} Cleardevicl ( ); printf (enter name); Move to (getmaxx( ) /2, getmaxy( )/2); For (i=0; str[i]; i++) { Spritf (msg, %c, str[i]); Out text (msg); Delay (1000); } } Changing the font style and size 1. void settextstyle (int font, int dir, int charsize) description of parameters font default FONT (0) TRIPLEX FONT (1) SMALL FONT (2) SANS SERIT FONT (3) GOTHIC FONT (4) SCRIPT FONT (5) SIMPLEX FONT (6) PRIPLEX SCRIPT FONT (7) COMPLEX FONT (8) EUROPEAN FONT (9) BOLD FONT (10) horiz dir (0) Vert dir (1)

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; Line (0, 0, x, y); Getch ( ); Closegraph( ); Restorertmode( ); y=getmaxy( )/2

Q.WAP which draws a line from 20, 30 to 100 pixels further & display the wordinate of line at its end point. Void main ( ) { Int gd, gm, ec, x, y; Gd = DETECT; Initgraph (&gd, & gm, c: \\TC\\BGI); Ec = graphresult ( ); If (ec! = 0) { Printf ( error); Exit (1); } Cleardericl ( ); Move to (20, 30); Sprintf (msg, %d %d, get x( ), gety( ) ); Outtext (msg); Linerel (100, 100); Sprintf (msg, %d %d, getx( ), get y( ) ); Outtext (msg); } Drawing Linee In Specific Width & Style Void setline style (int style, int pattern, int thickness) Style:- No 0 1 2 Constant SOLID-LINE DOTTED LINE CENTER-LINE meaning solid line line withdot & dash

3 4 Pattern:Thickners:-

DASHED-LINE USERBIT-LINE

line with dashes

It is always zero except when first parameter is userbit line. 1 THICK-WIDTH 3 NORM-WIDTH

Void main( ) { Int gd, gm, ec, I; Char * style [ ] = { solidline}, Dotted-line,----, Dashedline}; Gd = DETECT; Initgraph ( &gd, & gm, C: \\TC\\BGI); Ec=graphresult( ); If (ec != grok) { Printf ( error); Exit(1); } Deardvice( ); For (i=0; i<4; i++) { Spritf (msg, %s in normal width, style[i]); Outtext (getmaxx( )/2-20, getmaxy( )/2-10, msg); Setlinestyle (I,0, NORM-WIDTH); Line (getmaxx( )/2-50, getmaxy( )/2 +20, getmaxx( )/2 +50, Getmaxy( )/2 +100); Getch( ); Cleardevicl( ); } Restorectdevicl( ); } Defining Pattens in User Defined Way Io define a user bit line wee have to build a sixbit pattern. In this pattern wheever a bit is one the curresposing pixel in the line is drawn in the current drawing colour. For eg:65535 or

setline style (4, OXFFFF, NORM-WIDTH); this will draw a solid line, setlinestyle (4, Ox3333, NORM-WIDTH) this will draw a dashed line. Drawing Arcs Or Circles Or Rectangles 1. void arc (int x, int y, intstangle, int endangle, int rad) 2. void piesline (int x, int y, int stangle, int endangle, int rad)

3. void circle (int x, int y, int rad) 4. void rectangle (int left, int top, int right, int bottom) 5. void bar (int left, in top, int right, int bottom) Filling Image With Different Patterns Void set color (int) Void setfillstyle (int pattern, int style) Pattern:The pattern parameter signifies the pattern in which filing is to be made. value 0 1 2 3 Result Background color Solid Filling --------------------------

Name 1. Empty Fill 2. SOLID-FILL 3. LINE-FILE 4. LISLASH_FILE

5. SLASH-FILL 6 BKLASH-FILE 7. LTBKSLASH-FILE HATCH-FILE XHATCH-FILE INTERLEAVE-FILE WIDE-DOT-FILE CLOSE-DOT-FILE

4 5 6 7 8 9 10 11

WAP which draws a sectangle with white outline & red fill color & should display the fitling in all of the twelve patterns one at a time. Also name of pattern should be displayed with in the rectangle. Void main ( ) { Int gd, gm, ec, left, right, top, bottom, I; Char * style [ ] = { EMPTY-FILE, SOLID-FILE, ----, CLOSED-DOT-FILE}; Gd=DETECT Initgraph (&gd, &gm, C:\\TC\\BGI); Ec=grapgresult( ); If (ec !=0) { Printf (error); Exit (1); } Cleardevicl ( ); Left = getmaxx( )/2-100; Top=getmaxy( )/2-100 Right getmaxx( )/2+100; Bottom=getmaxy( )/2;

For(i=0; i<12; i++) { Setfill style (I, RED); Bar(left, top, right bottom); Rectangle (left, top, right, bottom); Outtextxy (left+50, top+50, style[i]); } }

FILLING CIRCLES & TRIANGLESS


1. void floodfill (int x, int y, int boundary) (x, y) a point with in the figure which has to be filled using flodfill also known as sad. Boundary color:- Color at which filling should stop. Filling Circles With Different Pattern Void main ( ) { Char * pattern = { EMPTY-FILE, --------, CLOSE-DOT-FILE}; Int gd, gm, ec, x, y, 0; Gd=DETECT; Initgraph (&gd, &gm, C:\\TC\\BGI); Ec=graphresult( ); If (ec! = grOk) { Printf ( error); Exit(1); } Cleardevice( ); X=getmaxx( )/2; y=getmaxy( )/2; For (i=0; i<12; i++) { Setcolor (GREEN); Circle (x, y, 100); Setfill style (I, RED); Floodfill (x, y, GREER); Setcolor (WHITE);

Outtextxy (x-50, y-50, patter[i]); Getch( ); Cleardivice( ); } Getch ( ); Restorecrtdevice( ); } Storing and Drawing Images On Screen 1. void getline (int, int, int, int, void *) 2. int imagesize (int, int, int, int) 3. void putimage (int, int, void *, int option) void getimage (int, int, int, int, void *) copies the bit image of specified postion in memoery 1st parameter indicates left coordinates 2nd parameterer to rd 3 parameter right th 4 parameter bottom 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 EMORY ON ON OUTPUT ON ON

ON OFF XOR-PUT ON OFF ON OFF ON OFF ON OFF ON OFF ON OFF THE END

OFF OFF ON ON OFF OFF ON ON OFF OFF ON ON OFF OFF

OFF OFF OFF ON ON OFF ON ON ON OFF ON OFF OFF OFF

OR-PUT

AND-PUT