You are on page 1of 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

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 by inheriting the members of base class it becomes possible to access them through the objects of derive class. Thus according to oop’s Encapsulation means building or wrapping up of data members and f n acting on those data members with in a single unit. In C++.BASIC PRINCIPLES OF OOP ENCAPSULATION Word has been derived from a word capsule which means multiple medicines packed in one single unit.function overloading and operator Overloading (ii). RunTime polymorphism:. The class which gets inherited is known as bass class and the class. pure virtual functions Ads tract classes (iii). Since a class allows us to hold data & functions within it are say that it supports the principle of encapsulation. The major advantage offered by principle of Inheritance is “rcusability and reliability” . So it a programmer define + to behave in above mentioned member we say that + behaves polymorphically .Virtual functions. POLYMORPHISM The word polymorphism is derived from combination of two words poly mcarning multiple and morph means the ability to have multiple forms.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. Inheritance :. 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. 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. Compile time polymorphism :. polymorphism is implemented in two way:(1).

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

Obj. i++) F=f*:.Int I. } CONTRUCTOR Constructor :. Cin >> n. Void getno( ). Public: Void init( ). }. Obj. } Void main( ) { Fact obj . display( ). Obj. Obj. Void display( ). } Void fact : : display( ) { Cout << “ Number =” << n. init( ). Void calculate( ).are special member f n of a class with the following properties . Cout << “factorial=” <<f. } Void fact : : getno( ) { Cout << “Enter a number”. Void fact : : init( ) { F=1.getno( ). For (i=1.get calculate( ). i<n. n. } Void fact : : calculate( ) { Int I.

They don’t have any return type not even void 3. They are automatically called as soon as the object of class is created i.1. } Void getno( ). They can’t be declared as virtual Any class which does not contain any constructor then compiler from itself supplier a constructor but it is hidden. They can’t be declared as static 5. Void display( ). at that time default constructors are called. their calling is implicit 4. }. Void calculate( ). They have the same name as that of the class 2. For programmer these constructors are default Class fact { } Constructors are automatically called even when not declared. Default contractors are destroyed as soon as we declare constructor Example :Class fact { Int I. Public: Fact( ) { F=1. an >> n.e. Void fact : : getno( ) { cout << “enter a no”. b. } .

j). Void show( ). Sal=k.Void fact : : calculate( ) { For (i=1.display( 0. Flaot sal. } Void fact : : display ( ) { Cout << “no=” <<n<<end1. } Void Emp : : show( ) { Cout << age << “ “ << name<< ‘ ‘ <<sal. }. } . Float). char *. } PARAMETERIZED CONSTRUCTOR Class Emp { Int age. Obj.getno( ). char *j.calculate( ). Char name[20]. Cout << “factorial=” <<f. Obj. Public: Emp (int. Obj. } Void main( ) { Fact obj. float k) { Age =I. Strcpy (name. i++) F=f*I. i<=n. Emp : : Emp (int I.

double) Void show (double. int. int) . Void main ( ) { Int choice. Void vol (int). No of Arguments 2. Swith (choice) { Case 1: Int s. Cin >> l >> b >> h. Vol (l. Case 2: Int l. Breck. Order of argument Int show ( ) Not allowed (return type differs) Void show( ) Compiler does not consider return type. Default: Cout < “wrong choice”. h). Cout << “enter side of cube”. Void show (int. Type of Argument 3. band h of alboid”.\. cin >> choice ( ). int) void show (int) void show (double) void show (int. h. int. Function overloading allows some function name in same scope but there should be some different in functions.b. Void vol (int. Cout << “Enter l. Cout << “select a figure”. Vol (s).FUNCTION OVERLOADING 1. other wise constructor can never be overloaded as they have no returns type. int ). Break. Cin >> s. Cout << “ (1) cube \n (2) cuboid”. b.

Public: Box( ). } . } Void vol (int l. //constructor for albe }. Box : : Box( ) { Cout << “enter l. B=j. int h) { Cout << “value of alboid=” << l*b*h. b and h of box”. H=k. } Box : : Box(int s) { L=b=h=s. it develops symmetry & incrrases the readability of program CONSTRUCTURE OVERLOADING Class Box { Int l. //constructor for user defined Box Box (int). } ADVANTAGES OF FUNCTION OVERLODING 1.} Void vol (int s) { Cout << “value of cube =” << s*s*s. b.h. int k) { L=I. Overload of remembering the name is transformed from programmer to compiler 2. int b. } Box : : Box (int I. int j. Cin >> l >> b>> h.

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

int) void swap (int*. Temp =p. 3. *q= temp. int 7p =. 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. Reference variable can not work with array 4. both variables get interlocked on each Other 3. } . swap (&a. cin >>a>>b. P=q.int&) void main( ) { int a. swap (a. multiple declarations for the variable p. int temp. cout << “Enter2no”.Cout <<a<< “ “ <<p. } } C++ pass by reference void swap (int7. Q=temp.intq) void swap (int*p. temp=*p. 2.b). POINTER TO REMEMBER 1. } void wsap(int&pint&q) { int temp. *p=*q. swap (a. P=q. cout << “enter2no”) cin>>a>>b. temp=p. cout <<a<< “ “<<b. cout <<a<< “ “<<b <<end1. &b) cout << a << “ “ <<b. always use pointer. we can not make array of reference variable int &p [4]’ C C pass by value pass by reference void swap (int. Cout << &a << “ “ <<&p. 2. int*) void main( ) void main( ) cout << “Enter2 number”. int*q) } } Int temp. reference variable is a technique using which programmer can allot multiple mames to same memory location. In case of array. b.b). } } Void swap(Int p. cin >> a >> b. int &p = a. Q=temp. In other words.

Max = a[0]. i<5.Note :. j<5. } } Class Box { Int l. 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. small. large. Cin >>a[i].By call it is not possible to call whether it is call by value or call by reference Q. int & main) { Int f. . large. } Void maximum (int a[5]. Min=a[0]. int &. Without changing the arcginal position of element of ht array. int&) Void main( ) { Int a[5]. Public: Box( ). I. For 9j=1. Maximum (int a[]. b. small). For (i=0. Cout << “smallert element=” <<small. i++) { If (* (a+j) >max) Max=* (a+j). } Maximum (a. Cout << “maximum element=” <<large. int &max. i++) { Cout << “enter elements of array”. h. Else if (* (a+j) <min) Min = *(a+j).

Box : : Box( ) { Cout << “enter l. int k) { L=I. B=j. b. } Box B4 (B1). } Void Box : : show( ) { Cout << L << “ “ << b << “ “ << h. B4.l. Box (Box &). } Box : : Box (int S) { L=b=h=s. Box (int. B B=p. } Box : : Box (Box &p) { L=p. Box B2 (10) Box B4 (B1) Box B2 = 10. int j. int). Void show( ). H=k. show( ). Box B2 (5. show( ).7. show( ) { Box B1. } Box : : Box (int I. B3. . }. B1.11). b1s l.b. Cin >> l >> b >> h.h. show( 0. } Void main ( ) B2. int.Box (int). Box B4 = B. Box B2 (10). b and h of Box”.h. H=p.

Call for copy constructor Box B4. } Void printline (char ch. i++) Cout <<ch. 1). // printline (‘*’. char. Printline(50). . Char j. Char grade. int=1) Void main ( ) { Printline ( ). Public: Stud (int. Void get( ). Void show( ). Float per. 10) // printline (‘1’. } Note. }. float=0. float k) { Age =I. Stud : : stud (int I. int n) { For (int i=1 i<=n.. 10). Per k.Default arguments must always be trailing arguments. DEFUALT ARGUMENTS Void printline (char =’*’. // stud (int=o. 1) Printline (‘!’. // printline ( ‘#’. B4 = B1 No call for copy constructor use of assignment operator other destination object is already made. char= ‘ .  printline (ASCII of 50. Class stud { Int age. char j. float). 1) Printline (‘#’).0).

p. } Note:. t. Stud p. show( 0. ‘A’. p. 75). 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. grade & per ‘. Cin >> age >> grade >> per. }.In class at same time it is not possible to have default argument constructor and default constructor. Emp( ). . Void show( 0. Char name [20]. get( ). } Void stud : : show( 0 { Stud main( ) { Stud t ( 15. Float sal.} Void std : : get( 0 { Cout << “Enter age. show( ). Public: Emp( ). DESTRUCTOR Are special member f n of class which have same name as that of the class but preceded with the symbol of field ( ).

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

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

calculate( ). . Note In C++. 4. } Cin. their calling is implicit 3. constructors can be parameterized. //Enter Key /9.e. Cin >> str. s.Else grad = ‘f’. } Student : : student ( ) { Free (Q). 2. Member of istream header file COMPARISION BETWEEN CONSTRUCTOR & DESTRUCTOR CONSTRUCTOR 1.getline (str. since constructors accepts parameters they can be overloaded & thus a class can have multiple constructors. show( ). Cout << “enter name”. are special member f n of a class having same name as that of the class. constructors are automatically called as soon as object of class is created i. int ). } Void student : : show( ) { } Void main( ) { Student s. s. Free(p). Prototype of get line ( ) Void get line (char *. 80). cin don’t accepts the space Void main( ) { Char str[20].

compiler does not has to leave the calling fn as it finds definition of fn being called their it self. the body of inline fn must be short & small 3. we can not pass parameters to a destructor. 2. s\reuces execution time & thus enhances the overall efficiency of program.5. if. thus a class can not have multiple destructor calling of destructor is always done in reverse or des of the creation of objects. 3. The overhead of maintaing the stack in belureen function call is seduced Thus declaring a function as inline increases the execution Speed. as they don’t accept parameters we can not overload then. are special member fn of class having same name as that of the class but 2. inheriting of destructor is also not possible we can have virtual destructor in a class. 7. while. 6. constructors are called in the orders in which objects are created. dowhile do. DESTRUCTOR 1. INLINE FUCNTIONS Inline functions Are those fn whose call is replaced by their body during compilation. 5. constructors can not be declared as virtual. But two ptr must be considered before declaring a fn as inline 1. 1. 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. it should not contain any complex keywords or keyword or statement like for. constructors can not be inherited. Declaring a fn as inline has two major advantages. 4. 6. 2. . 7. The definition of inline function must appear before its call i. if a non member fn is to be made inline then its declaration & definition must appear about main as a single unit.e.

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

} Void display( ) { Cout <<a<<end1. cout <<a<<end1. A++. void main ( ) { display( ). } void display( 0 { static int a. Void main( ) { Display( ). display ( ). a++. scope (accessibility) storage default 1. } o/p 3 garbage values will be generated . life (persistence) 3. } o/p  o 1 2 Auto Void display ( ). Default value 2. display( ). Display ( ). Display ( ).auto garbage (automatic) 2. 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 ( ). register 4. static 3.STORAGE CLASSES Storage class decides the following 1.

of student objects currently in the memory. Static int b.STATIC DATA Static data members with in the class Class data { Int a . 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. static data members arrive in memory even before objects of the class get created. Finally provide appropriate members fn to initialize & display the values of Roll no. The member roll should keep the roll no. WAP to create a class c/o student having two data members roll & count. a int Data : : b. 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. d1 D2 static variable don’t wait for creation of object. Static int count. Public: Student (int i) { 0 a b . Class student { Int roll. In other words size of object is always calculated by summing up sizes of non static members. allocated to every student object while the members count should keep track of total no. 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. 3. before object creation memory is allocated for then of class 1. & count. }.

} Student ( ) { Count. Student P=20. Student Q=30. } } STATIC FUCNITON <obj-name>. show( ). Y. Void main( ) { Student S=10. static f n can never non –static data numbers. show( ). Student Y=50. show( ). constructor & Destructor can never be made or declared as static. ++ count . Cout << “total objects alive =” <<count. { Student X = 40. S.Roll=I. . P. show( ). But reverse is true. show( ). 2. X. } Void show( ) { Cout << “Roll no=” <<roll<<end1. Int student : : count. <function-name> Syntax <class-name> : : <function-name> DRAWBACKS OF STATIC FUNCTIONS 1. } }. Q.

Class student { Int roll. { Student X(40). Q(30).Create a class c/a employa having data members for storing age. Static int count. Y(50). Provide a member f n to initialize . } Program :. } }. Student : : show( ). } Student : : show ( ). Also provide another member which stores the next id which will be allocated to next incoming object. P(20). ++arunt. Getch( ). Student : : show( ). Public : Student (int i) { Roll =I. name & id. } Student : : show( ).X Count << “total objects alive =” <<count. Void main( ) { Student S(10). } Static void show( ) { Count<<Roll. } Student ( ) { Count. Int student : : count.

Static void init id( ). Int id. Class Emp { Int age. char *). Public: Static void init( ) { Id=n-id. Public: Employce (int. } Emp( ) { Cout << “enter age. Char name[20]. } Solution :Class Emp { Int hae. Cin >> age >> name.this variable with its initial value & also provide appropriate constructor & member f n for initialized all other members of class. ++n-id. Char name [20]. Static void get next id( ). Id=n-id. . Static int n-id. name”. } Void show( ) { Cout <<age<<name<<id. Static int n-id. Void show( ). Int id.

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

Cout << “Add of calling object=” <<this. Cout << “Add of calling object =” this.show( ).get( ). } } Void main( ) { Emp E.THIS POINTER Class Emp { Int age. f. Float sal. Public : Void get( ) { Cout << “enter age. } Void show( ) { Cout <<age<<name<<sal.show( ). Compiler initialize it with base address of calling object. e. This Pointer .get( ). 2. Every member f n of class has this pointer. f. name & sal”: Cin >> age>> name>>sal. Char name[20]. No need to declare & initialize this pointer. e. f.’ } 1.

int( ). Box (Box &p) { L=p. thisb=j.l. Box (int. }. B=j. H=k. Public: Box( ). *this=p. } Box : . Whenever the object of a class puts a call to any non static member f n of that class. int. thish=k.This is a special pointer available in every member foundation of a class except static member f n of a class. the this pointer available in that member f n implicitly starts pointing to the address of calling object. int k) { L=I.b.h } . Box : : Box( ) { Cout << “Enter l. } Box : : Box (int I. h. By default class has 3 “this” pointer. and h”. b. B=p. Constructor copy constructor Destructor Accessing Data Member Using ‘this” Class Box { Int l. Thus we can say that a “this” pointer always points or referr to the aurrent object. Void show( ). thisl=I. Box (Box &). int j. Cin >> l >> b >> h. H=p. b.

Const variable “ pointer “ parameters C “ data members of class 5. It is a constant pointer. } Void main( ) { Box B1. Box = *q. 7. B2.14 Const variable are initialized at the pt of declaration menns they are read only variables & their values can not be manipulated. show( ). Cout << this  l << thisb << this h. 3. Box B3 = B1. } LIMITATIONS OF THIS This pointer always points to calling object thus it can not incremented or decremented.Void Box : : show( ) { Cout << l << “ “ <<b<< “ “ <<h. . B3. Box B2 (5. 4. Q = this+1 valid Q=++this notvalid USING THE CONST KEYWORD 1. “ member f n of a class C++ Const Variables Void main ( ) { Const float pi=3. 2. 11). show( ). show( ). B1.

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

h } Const data members of class Class circle { Int rad.14). } Void show ( ) const { Count << “Rad=” <<r++ << “Area=” <<a. .B=p.b H=p.14. Class circle { Int r. // const var are initialized at the point of declaration thus this is not valid statement Circle (int r) : pie (3. Void get (int x) { R=x. } Void cal-area ( ) { A=r * r * r * 3. 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. Float a. Const flaot pi X. } If const is there then value of r will not be changed other wise at last it will be incremented.

Public: Void get( ) { . Public: Data (int I. int j): x(i+j). y(j). reference variables 3. 1. y(x+i).INITIALISES Inialises It is a special syntax allotted by C++ used to initialize there thing . 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.10) X=5 Y=10 Data D(7. const data members with in the class. 2. h. int j): x(i). y.14) X=21 Y=28 PASSING OBEJCTS USING POINTER Class Box { Int l. b. { } } Ist case Data D (s. calling parameterized constructor of the base class from derived class. { } Data (int I.

get( ). If (x= = y) Return (0). y. B2. else if (ans >=1) cout << “B1 is greater”. B1. show( ). B2. get( ). Else Return (+) } Void main( ) { Box B1. b. X= l*b*h. B2. h. Else if (x>y) Return (1).// same as previous } Int compare (Box *) }. } Void show( ) { // same as previous. B1. show( ). compare (&B2). Y=P l* pb* ph. And = B1. Int ans . Int Box : : compare (Box *p) { Int x. Public: Void get( ) { // same as previous. if (and= =0) cout << “equal”. else cout << “B2 is greater” } Passing Objects by Reference Using Reference Variable Class Box { Int l. } .

y. 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. compare (B2). If (x==y) Return (0). X = l*b*h. . ATTRIBUTES OF FRIEND FUNCTIONS 1. protected members of the class. Int and. } Void main( ) { Box B1. } FRIEND FUNCTIONS A friend function is a special function which despite of not being member f n of class has full access to the private. Int Box : : compare (const Box &P) { Int x. Ans=B1. B2.get( ).h. Y = p. else cout << “B2 is greater.Int compare (Box &). else if (ans >1) cout << “B1 is greater. Else Return (-1). If (ans= =0) Cout << “equal”. }. B1.show( ). B1.show( ).get( ). B2. Else if (x > y) Return (1).l*p.b*p. B2.

4. Char grade.2. } Demonstrating the use of friend function . neither the name of the object nor dot operator appears toward its left. S. whenever a friend f n is defined neither. Grade & per”. 3. Friend void show (student). 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:. } Void main( ) { Student S. Show(S). Moreour the keyword friend also does not appear. whenever a friend fn is called. Float per.roll<< “ “ << P.grade<< “ “ <<P. Public: Void get( ).per. } Void show (student P) { Cout << p. get( ). It may however accept – the object as a parameter whose members it wants to access. 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. Cin >> roll>> grade>>per.// Demonstrating the use of friend function Class student { Int roll. Void student : : get( ) { Cout << “enter roll. the name of class nor scope resolution operator appears in its definition. }.

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

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

feet = feet +P. Else Cout << “equal”. Int in cher. feer += temp. Compare (obj1. Obj2.Y. Obj1. . } ADDING TWO OBJECTS OF A CLASS USING MEMEBR FUCNTIONS Class Distance { Int feet. Beta Obj2.Else if (B.inches= inches + P. } }. get( ). If (temp.X) Cout << “Greater=” << B. obj2). Public: Void get( ) { Cout << “enter feet & inches”. Cin >> feet >> inches.inches. set( ). Distance Distance : : add (Distance &P) { Distance temp. Temp. } Distance add (Distance &) Void show( ) { Cout << “feet=” << feet<< “inches=” <<inches. inches/12. } Void main( ) { Alpha Obj1.Y> A. feet. Temp. inches>=12) { temp.

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

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

Syntax:<ret-type> operator <op-symbol> (arguments). Operator Overloading can be done 1. Overloading Of Unary Operator As Member Function Of The Class (Pre Increment) Class counter { Int count.e. f n call which are given using operator overloading are much more easy to interpret as compared to conventional function calls.show( ). } Counter (int c) . 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. D2) D3. Public: Counter( ) { Count =0. Friend (ret-type> operator <op-symbol> (<arguments>). making use of friend function. The major advantage offered by operator overloading is the simplicity in readability of the call i. } 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.get( ).D2. D3 = add (D1. Making use of member function 2.

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

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

} Friend void operator ++ (counter &). count = count++. C2 = c1++. Void operator ++ (counter &C) { ++ c. } Void main( ) { Coun c1 = 10. Temp. return (temp). show( ).count++. C1. c2. show( ).count Return (C). } Void show( ) { Cout << count << end1. } Counter (int i) { Count = I.Counter temp. }. } Overloading Unary Operator As Friend Of The Class Class counter { Int count. Public: Counter( 0 { Count=0. count = c. } Void main ( ) Or counter temp. . Return (temp). C2. temp.

C2= ++ C1. C1. Public: Friend counter operator ++ (counter &). return (temp). } Count (int i) { Count = I. C1. show ( ). temp. show( ). C1. Void main( ) counter & operator ++(counter &c) { { Counter c1 =10. count. C2. Class counter { Int count. } Note:when unary operators are overloading using member function then don’t accept any argument but when they are overloaded using friend fn then they have one argument of type object (class). C2. show( ). C2. counter temp. } } Overloading Binary Operators As Member Functions Of The Class . C2. count = C. = ++(). show ( ). Counter { Count =0. show( ). C1. show( 0.{ Counter C1 = 10. { Void show( ) { Cout << count << end1. c2. } }.

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

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

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

D3. Cout << “enter an integer”. show( ).operator = = (D2) ) Class Distance { Int feet. Int n. D3 = n+D1. II } Note:II can not be done using member function becoz n is an integer and only an object can call function not integer. Cin >> feet >> inches. // can be done using member fn & friend fn D2. inches.Distance D1. D2. get ( ). Cin >>n. D1. Public: Void get( ) { Cout << enter feet & inches”. } . Cout << “Enter an integer”. Cin >> n. 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. I D2 = D1+n. // not possible through member fn D3. } Void show( ) { Cout << feet << “ “ << inches. show( ).

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

S3 = s1 +s2. s.str[i] = str[i]. for (j=0. j. } Void show( ) { Cout << str. } String operator + (string S) }. String s2 = “How are you ?”. } s3. S1.(dot operator)  member access operator (already overloaded) .str[j]. show( ). Int I. Assignment :WAP which compares two string objects & checks which one is greater. } String (char *P). show( ). s2. P). i++. String string : : operator + (string S) { String t. i++) t. j++) t. return (t). { Strcpy (str. show( ).str[j]. } Void main( ) { String s1= “Hello”. For (i=0. String s3.String ( ) { Str[0] = ‘\0’. Operators Which Can Not Be Overloaded 1> .str[i] = s. str[i].

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. brings memory from local heap 5. Necessary to include the header file 3. Maximum memory that malloc can allocate = 64KB 6. 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.(i) (ii) new <data – type> new <data-type> [int]. Constructors are called dynamic Constructors. It takes no. Malloc retirens the address of Allocate block in from of (void*) Thus its return value has to be type Casted accordingly 7. of bytes as parameter 4. . It is a function 2.:: (scope resolution operator) it already works on classes we overload only those operators which works on primitine and not on non prin 3> ?: (conditional Operator) It requires there arguments overloading of operators atmost can take 2 argument 4> >* Pointer to member operator 5> Size of operator 2> DYNAMIC MEMORY ALLOCATION (DMA) MALLOC 1. Syntax for new. 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. when malloc fails it returns null 8.

3000 P Syntax for deletes .Allocations Of New :1. P= new int (10). 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. P=new int [10]. // deletes one block of data type 2. new allows programmer to initialize the memory allocated but malloc does not provide nay such feature 2000 P 2. 3000 2000 10 2002 Here value 10 denotes that programmer is interested in creating memory for elements 1.. int &P. Cout << *P. Delete P. int * p. Void main ( ) { . Delete <ptr-name>. // deletes whole allocated memory Eg:.float *P. Delete [ ] <ptr-name>. Finally it should display the largest element & delete the array. Delete P.

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

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

} Void show( ) { Cout << age << “ “ << name<< “ “ <<sal. Void main( ) { . } DYNAMIC OBJECTS Allocating memory for class with the help of new. reverse str(S2). show str( ). getstr ( ). S1. } Void main ( ) { Int n.String : : string ( ) { Delete [ ]P. Public: Void get( ) { Cout << “enter age. Cout << “How may character”. S2. String S2 =n. Char name[20]. S1. Cout << “ Array destroyed”. Cin >> age >> name >> sal. S1. } }. Cin >> n String S1 =n. show str( ). Float sal. name & sal”. Class Emp { Int age.

} p get( ). Char anem[20]. } Void show( ) { Cout <<age<< name<<sal<<end1.Emp *P. p show( ). If (p= =0) { Cout << “Memory Insufficient”. name and sal”. getch ( ). Class Emp { Int age. } 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. Exit (1). Float sal. Then it should accept values for each object and finally display them. } }. Void get( ) { Cout << “enter are. Cin >> age>> name>> sal. . P=new emp. delete p.

i<n. } For (i=0. name and sal”. Cin >> age>> name>> sal. Char name [20]. Cout << “how many employees?”. Getch( ). } . i<n. } Enhance the above program so that after accepting records of n employees. Exit (1). If employee name is not available then program should display the message record not found. get( ). or p[i]. Delete[ ]p. Public: Void get( ) { Cout << “enter age.Void main( ) { Emp *p. Your program prompts the user to enter another name & display the record of that employee only. Float sal. Cin >> n. Class Emp { Int age. Int I. or p[i]. show( ). } Void show( ) { Cout << age<< name << sal. n. If ( p = =0) { Cout << “error in crating objects”. New Emp [n]. i++) (p+i)  show( ). For (i=0. i++) (p+i)  get( ).

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

} Void show( ) { Cout << age << name << sal. (this +i)sal (this+j)sal. Cin >> age >> name >> sal. { Int age. T= (this+i)  sal. For (i=0. i++) { For (j=i+1. or Emp F. I. Strcpy ((this +i) name. Void Emp : : sort (int r) { Int j. Public: Void get( ) { Cout “enter age. }.WAP which creates an array of n objects. Char name [20]. *(this+i) =* (this+j). (this+jname). i<r. Float sal. name and sal. temp). Char temp [20]. *(this+j) = F. 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. } Void sort (int). (this +i) age = t. (this +i)  name). t. Strcpy ((this+j)naem. T=(this+i) age. j<r. j++) { If (str cmp( (this +i)  name. . (this +j)  name)>0) { Strcpy (temp.

Cin >> age >> name >> sal. Char age. Void main ( ) { Emp *P. P=new Emp. Char name [20]. float k) { Age = I.(this+j) sal=t. Emp( ) { Cout << “enter age. } }. *q. } //closing of it } // inner for } /outer for } // closing of function DYNAMIC COSNTRUCTORS Class Emp { Int age. } Emp (int I. } Void show( 0 { Cout << age << “ “ name “ “ << sal. Public. . Float sal. Strcpy (name. Sal = k. j). char *j . } Emp( ) { Cout << “Object destroyed”. name and sal.

200000).Q=new Emp (30. p show( ). 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. Thus if memory is freed for a dynamic object it can only be done through delete operator. “vineet”. q show( ). call for delete is not present so memory block still remains in RAM & might be collected in future through garbage collection. Terms Used For Dynamic Objects Live Object :. delete p. Since in above code. delete q. Hierarchial Inheritance A .Those object which are initialized using constructor are constructor are c/o live objects. } Note:. Multiple Inheritance A B 4. Single Inheritance A Base class 2. Multi level Inheritance A indirect base class of C B Derived class B c base class of C 3.The above Program will not call the destructor of the class even at the termination. Partially live objects INHERITANCE 1.

Cin >> l>>b>>h. b.C B C 5. h. } Void show( ) { Cout <<l<< “ “ << b<< “ “ << h. Base class . Public: Void get( 0 { Cout << “enter l. band”. 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.

} }. Public: Void set( ) { Cout << “enter material name”. 3. } Void display ( ) { Cout << “material =” << type.e. they can be accessed through the function of derived class as well as by objects of derived class. 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. Obj. 2. Class carton : public Box { Char type[20]. 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. Obj. All the public members of base class becomes public members of derived class i. Cin. 20). EARLY BINDING:- . Void main( ) { Carton obj. set( ).} }. Obj. display( ). } Accessability Rules When Mode Of Inheritance Is Public When a base class is inheritance in public mode then :1. Get line (type. get( ). show( ). Obj.

It is a prours which is executed during compilation in which compiler binary the fn body with the fn call i. Overriding Scope must be different By the classes related by Inheritance Prototype of functions Must be same . fn provided by base class has same prototype in derive class but in different body. 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.e.e. Early binding is always an action until & unless keyword virtual is used infront of the fn return type. 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:- . function calls which are bound using early binding get executed at a fastest speed as compared to late binding fn calls. we can say it is early binding. In other words. 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. overloaded fn calls and overloaded operators The major benefit of early binding is speed of execution i. 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.

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

Class Num { Protected : Int a. } }. Obj. .e. All the protected members of base become private members of derive class i. Void main ( ) { Add Num obj. Public: Void get( ) { Cout << “enter a and b”. Cin >> a >> b./ add( ).e. Obj. All the public members of base class become private members of derive class i. set( ). they two can only be accessed through the function of derive class but not by objects of derive class. they can be only accessed through fn of derive class but not by the objects of derive class. } Void show( ) { Cout << “a = “<<a<<end1. display( ).Void display( ) { Show( ). Cout << “sum=” <<c. b. 2. } PRIVATE MODE OF INHERITANCE When a base class is inheritance in private mode then:1. Obj/. 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. 3.

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

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

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

which should accept values in the array & display its values respectively. 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. } Assignment :Create a class c/a array which contains an integer array of size 10. D. Void main( ) { Dec counter D.. Now create a derive class of array c/a sortarr. D.-( ) { . show( ).{ Public: Void operator . D.count.h> #include <stdlib. 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..show( ). . D.show( ).int(10). } }. ++D.h> Class Array { Protected: . The class should have two member functions called get arr and showarr.D.

Public: Void get( ). i<5. A [j+1] = j. Void display( ). j++) { If (a [j] > a [j+1]) { T = a [j]. A [j] = a [j+1]. i++) Cin >>a[i]. } } } } . For (i=0. j. i<5. } Class sortarr : public Array { Public: Void ascsort( ). t. } Void Array : : display ( ) { For (int i=0. Void sortarr : : arcsort ( ) { Int I.Int a[10]. i++) { For (j=0. j<4. Void Array : : get( ) { Int I. }. i++) Cout << “\n elements are =” << a[i]. Cout << “enter array elements”. i<5. Void descsort( ). }. For (i=0.

j. i<5. j++) { If (a[j] <a [j+1]) { T=a[j]. Switch (ch) { Case (1): Sr. Cout << “\n \t Enter (5) for quit”. Cin >> ch. j<4. Cout << “\n \t Enter (4) sort in Descending order”. For (i=0. Break.display( ). Cout << “\n \t Enter (3) sort in Ascending order”. Cout << “enter choice”. t. Case (2): Sr. Sortarr sr. Clrscr( ). Do { Cout << “\n \t Enter (1) for Input data”. .Void sortarr : : descsort( ) { Int I. A[j]=a[j+1] A[j+1] = t.get( ). Break. Cout << “\n \t Enter (2) for Display Data”. Int ch=0. i++) { For (j=0. } } } } Void main( ) { Clrscr( ).

Break. Public: Void get( ) { Cout << “enter a =”. } Void show( ) { Cout <<a << end1. sr. Break. } Void display( ) .ascsort( ). } Sr. } }. Cin >>a. Cin >> b. Class Base2 { Protected: Int b. MULTIPLE INHERITANCE Class Base 1 { Protected: Int a. Public: Void set( ) { Cout << “enter b=”.Case (3): Case (4): Case (5): Exit(1) } } while (ch !=5) Getch( ).descsort( ).

{ Cout <<b << end1. print( ). Class Base1 { Protected: . accept( ). } }. add( 0. Public : Void accept ( ) { Get( ). Obj. Cout << “sem =” <<c. Obj. Void main( ) { Drv obj. Obj. } }. } Program :Base & derive having the function with same name & arguments. } Void print( ) { Show( ). } Void add ( ) { C = a+d. Class drv : public base1. Display( ). Set( ). public base2 { Int c.

public Base2 { Int c. Public: Void get( ) { Cout << “enter a=”. } Void add( ) { C= a+b. Public: Void set( 0 { Cout << “enter b=”. Class Base 2 { Protected: Int b.Int a. Set( ). Public: Void accept( ) { Get( ). } Void show( ) { Cout <<b<<end1. } }. Class drv : public Base1. . } Void show( ) { Cout << a << end1. Cin >>a. Cin >> b. } }.

Error ambiguity error } }. Obj. it a base class contains a constructor and destructor as well as derive class also contains constructor & destructor. Base2: : show( ). Void main( ) { Drv obj. constructor of base class gets executed first followed by constructor of derive class and the destructor is called in reverse order i. accept( ). } Base( 0 { Cout << In base’s destructor “<<end1. Obj. Thus we can say constructor are always called in the order of inheritance and destructor are called in reverse order. } base1: : show( ). Obj. } }. Role Of Constructor & Destructor In Inheritance As a basic rule in inheritance. print( ).} Void print( ) { Will show show( ).e. Class Base { Public : Base ( ) { Cout << In base’s constructor” <<end1. add( ). . the destructor of derive class is called first followed by the destructor of base class. then when object of derive class is created.

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

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

} }. Drv obj2 (20. Void main( ) { Drv obj1 (10. int q) : base 1 (p). base2(q) { C=a+b. } Void display( ) { Cout << b.Class Base2 { Protected : Int a. Class drv: public base1. 70). Cout << “their sum =” << c. 20). print ( ). public base2 { Protected : Int c. } Void print ( ) { Show ( ). } Note :- . Display( ). print( ). } }. Obj1. Obj2. Public: Base2 (int j) { B = j. Public: Drv (int p.

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. int j): Base1 (i) { B=j. Public: Base 1(int i) { A=1. } Void display( ) { Cout << b << end 1. public Base2 { Protected: Int c. } }. Class Base2 { Protected: Int b. Constructor Calling In Multilevel Inheritance Class Base1 { Protected: Int a . Public: Base2 (int I. Class drv : public Base1. Public: . } Void show( ) { Cout << a << end1. } }.

} Void print ( ) { Show( ). Obj1. Same is the case with destructor. 60). Obj2. Now since the private data of class is not passed on to its derive classes. } }. } Note Constructors can not be inherited :Constructors are special member fn which are exclusively used for initialing private data members of class. so the functions which explicitly initialize then (constructor) are not inherited. b: Public : Num (int I.Drv (int x. print( ). Drv obj (50. Display ( ). print( ). B = j. 20). HIERARCHIAL INHERITANCE Class num { Protected : Int a. y) { C=a+b. int j) { A = I. int y) : base2 (x. Void main ( ) { Drv obj(10. Cout << “their sum=” << c. } .

Cout << “ sum =” <<c. Cout << “b=” << b.Void show( ) { Cout << “a =” << a. 20). } }. y) { b= a – b. } }. { Void show( ) { Num : : show( ). } Void show( ) { Num : : show( ). int y) : Num (x. } }. Public: Add num (int I. . Class Add Num : public Num { Int c. show( ). intj) : Num (I. j) { C=a+b. Add obj. 70). Class Diff num : public Num { Int d. DiffNUm diffobj (30. Public : Diff Num (int x. Void main( ) { Add Num addobj (10. Cout << “ Difference =” << d.

Cout << “sum =” << obj. Obj. c. Show( ). }. Obj.d= obj a + obj. b = 20 Obj. Class drv1 : virtual public base { Public: Int b.Diffobj. Class drv2: virtual pubic base { Public: Int c. Class drv3 : public drv1. Void main( ) { Drv obj. c 30. Obj. }. a =10.d. } GRATING ACCESS Class Data . } HYBRID INHERITANCE Class Base { Public: Int a.b + obj. }. public drv2 { Public: Int d. }.

Foreg:Class Bank { Public : Void deposit( ).{ Private : Int a. Bank : : with draw. POLYMORPHISM Class Base { Public: Void show( ) { Cout << “In base ‘& show”. Class drv : protected Data { Public: Data : : C // bring C in public mode instead of protected }. Void withdraw( ). Protected : Int b. Class saving – acct: Private Bank { Public : Bank : : deposit. Void int-cal( ). Public : Int c. . }. }. } }. }.

Ptr  show( ). Class drv1 : public Base { Public : Void show( ) { Cout << “In drv1’s show”. } VIRTUAL FUNCTION & MULTILEVEL INHERITANCE Class Base { Public: Virtual void show( ) { Cout << “In base’s show”. *ptr. Void main( ) { Base b. Ptr  show( ).Class drv : public Base { Public : Void show( ) { Cout << “In drv’s show”. Drv d. } }. Ptr = & b. Ptr = & d. } }. Class drv2: public drv1 { Public: Void show( ) . } }.

. } Note :Top level class ptr can access member of lower level class. b. 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. 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. if a fn is preceded with keyword virtual then if never become the past of early binding & compiler delays its binding until runtime. Ptr  show( ). Ptr = &d2. Thus all the decisions regarding the call and the body to be executed are taken at runtime. Ptr = & d1. derive should override the virtual function of base class if it wants to place its own definition of virtual function. If the calling pointer is storing the address of base class object then base’s version of virtual function will be executed & if it pointing to an object of derive class then derive version of virtual fn is executed. Ptr  show( ). Drv1 d1. } }. Ptr  show( ). Virtual is mandaroty in base show as function is originally from base. This is because pointer of base class can access only those function of derive class which are overridden in the derive class but not those which are hidden or added by derive class. Void main( ) { Base * ptr. In other words. 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. Drv2 d2.{ Cout << “In drv2’s show”.e. Ptr = & b.

obj2 VPTR }. Ptr  f3( ). 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.Internal Working Of Virtual Function Class A { Int a. . 2 bytes for VPTR Ptr  f2( ). Ptr = & obj2. Void f2( ). Public: Void f4( ). 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. Class B : public A { int x. Public: Void f1( ) { } Virtual void f2( ) obj1 VPTR a { } }.

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. Data (int ). } Void Data : : show( ) . Lastly within the VATBLE it executes the virtual function called. Return (D). Data : : Data (int i) { A = I. VVPTR:(Virtual Void Pointer) For every class which contains a virtual function special pointer is created by the compiler known as VVPTR. Thus every object of class containing virtual function has its size incremented by2. which is used for pointing to the virtual table.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. This table is then consulted by the compiler when a call for virtual function is encountered during runtime. } Data Data : : get object( ) { Data D (10). Void show( ). Public: Static Data get Objects( ). }. 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. Now whenever compiler encounters call for virtual function through a pointer. Class Data { Int a . 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.

Function Overriding 2. Function Overloading 2. Class Rectangle : public Figure { Public: . Cin >> dim1>> dim2. Public : Void get( ) { Cout << “enter 1st & 2nd dimension”. } }. Early Binding Virtual Inheritance Run Time Polymorphism 1. D. Operator Overloading 3. Late Binding avoids multiple copies Polymorphism (converts parly binding to late binding) Class Figure { Protected: Int dim1. show( ). Polymorphism Compile Time Polymorphism 1. } Void main( ) { Data D = Data. Get object( ). Virtual Function 3.{ Cout << a. } Note When only one object of class is created then that type of class is c/a single to n class. dim2.

Cout << dim1 * dim2. Figure F. Void main( ) { Figure *p. p area( ).Void area( ) { Cout << “area of Rectangle=”. p get( ). triangle T.If a virtual functions declarations is equated with zero then it is known as pure virtual fn. it we do not want to provide any definition for a virtual fn wee can equate with zero then it will be known as . Class Triangle : public Figure { Public: Void area( ) { Cout << “area =” <<’5 * dim1 *dim2. } }. p=&R. P = &F. } PURE VIRTAUL FUNCTIONS Def:. p area( ). p get( 0. } }. p get( ). p area( ). In other words. p = & T. rectangle R.

Cout << “ p constructed!”. 3.pure virtual fn.Constructors can not be virtual since link between VPTR VTABLE is made by constructor Virtual Destructor:Class Base { Protected: Public: Int *p. 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. ABSTRACT CLASS 1. which stores the address of virtual function has no body it can not have memory address & thus it can not places in VTABLE. If a class contain at least one pure virtual fn than it is known as abstract Base class. Thus by definition a pure virtual fn is one which has no body define with in its own class or base class. we can never create any object of abstract class but we can always create its pointers. So to prevent any accidental calls to a non-existing pure virtual function compiler prohibits the creation of an object of an abstract class. This is because whenever an object of a class containing virtual function is created a VTABLE is setup by the complete. 2. } Virtual . Cout << “memory deallocated”. } base { Delete [ ] p. Note:. base( ) { P=new int [10].

Class drv : public Base { Int *q. } Drv( ) { Delete [ ] q. FILE – HANDLING (STREAM I/O) Flow of data If flow of data is from program towards device then o/p stream eg. is used. Since it is not possible to leave empty body of destructor since at the time of call of destructor same activity must be performed. Public : Drv( ) { Q = new int [10]. Monitor / Buffer Monitor . Cout . Ptr = new drv. Delete ptr. Cout << “ q constructed”. } }.}. Void main( ) { Base *ptr. Cout << “memory deallocated for q”. } Destructor can not be declared as pure virtual. If flow of data is from device to program then i/p stream eg cin is used.

Step 4 Close the file.Of stream obj. is a class whose objects can be created for reading data from file. txt”). Of Stream:2. Fstream :- Hard disk If a class whose objects can be created for writing data to secondary memory of file. Step 3 write the data through the object in file. obj << “Hello”. 1 (a) Of stream Obj ( “Data.close ( ). Txt”). put (‘H’). Step 2 Connect the object with file on your system. C++ Implement Of Above Steps Step 1 Step 2 Step 3 Step 4 (a) (a) (b) Of stream obj. Open ( “Data. It Stream:3. . Steap Required For Writing Data In File Step  1 Create the object of “Of stream” class Eg:. obj. obj.Input stream C++ Program Input stream output stream output stream Hard-disk Classes Available In C++ For File Handling 1. obj. whose object can read / write the data in a file.

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

While (str[i]) { Out. Retruns I if not connected Returns 1 if conceted . Solution :Void main ( ) { If stream in ( “message. If (!out) { Cout << “file can not be opened”. Text”). Int i=0. } 1 Note:isopen ( ) 0 1 Fail( ) 0 Que:. Exit(1).{ Of stream out ( “Message. } Char str[80]. If (! in) { Cout << “filoe can not be opened”.txt”). Getch ( ).qetline (str. Out. Close( ). 80).put (str[i]).WAP to open the file created by the previous program. Cout << “enter a line of text”. Getch ( ). } Cout << “file written successfully”. I++. Cin. Read it on character by character basic & display its contents on the screen. Exit(1).

seekg (0). Int i=0. Exit(1).get line (str.WAP to open a file c/a “Data. While (str [i]) { Ch=str[i]. } Que:. ios: : out | ios: : in). Cout << ch. 80).eof( ) ) { Ch=obj. Char ch. Cin. While (! In.txt”.put (ch). } Char str [80]. } Getch( ).} Char ch. Cout << ch. Cout << “enter a line of text”. Obj. I++. Void main( ) { Fstream Nisha ( “Data”. If (! Nisha) { Cout << “error opening file”. 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 .enf( ) ) { Ch=in. } Obj.get( ). In.close( ).get( ). } . While (! Obj.

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

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

Otherwise data gets Erased and pointer is placed at the beginning. ios : : out (Default mode of ofstream) If file is not existing then it is created. pointer is placed a the beginning otherwise error is generated. 6. 80). In this pointer can move forward and backward. Used with ios : : out Truncate previous data & brings pointer to beginning. ios : : trunc Needed only in fstream. ios : : ate (ate stands for at the end) Allows updations as well as adding of new data. 2. If file is existing. ios : : in 5. } } FILE OPENING MODES 1. ios : : nerplace Used with ios : : out if file is existing do not replace it otherwise create it.getline (text. Cout << “enter lines and press enter on new line to stop”. 3. 4. 7. ios : : nocreate . Obj << text << end1. } Char text [80].Exit(1). ios : : app It can not alter previous contents but can add new content at the End of file. If (strlen (text) = =0) Break. While (1) { Cin.

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. address of variable whose data is to be Written int ) no of bytes to be written Int a = 23091 . Char b = ‘x’. Char d. Cout <<d. BINARY I /O Void write Of stream Member (char *. size of (char) ). Int read (char *. read (&d. size of (int) ).seekg(0). Cout << c. Obj. read ( (char *) &c. Obj. size of (int ) ). Obj. Float sal. Reading and writing class objects Class Emp { Int age. ios : : binary If we want to write data in binary form. 8.Used with ios : : out if file is existing overwrite it otherwise do not create it. Public: Void get( ) { . write (( char *) &a. Char name [20]. Int c. Obj.

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

ignore( ). we want to read file successively to eof we must clear the flag Obj. Fstream obj1 ( “Ekta. ios : : out | ios : : in | ios : : trunc | Ios : . 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. clear( ). If (! Obj) { Cout << “error”. txt”. cin. Q. cout << “Any More (Y/N)”. seekg (0).read (char *) &E. } Typical Feature Of Read:Note :If in any ane program. binary). size of (Emp)). While (opj. Exit(1). getch( ). cin >> choice. } while ( ch = = ‘y’). WAP to write multiple records of type emp in a file.close( ).show( ). { e.write ((char *) &E. . seekg (0). Obj. obj.get( ). Obj.} Char choice. } Char ch. obj. size of (emp)) E.

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

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

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>

} Void main ( ) { Int arr[ ] = {7. T c. 11. 3. 8}. int n) { Int I. T b. Public: Void get( ) { Cin >> a >> b. } Void add ( ) { C = a+b. T max = *a.T greatest ( T *a. 8. } CLASS TEMPLATE Template <class T> Class Data { T a. Cout “max float=” << max (brr. } Return (max). i++) { If ( * (a+i) > max) Max = * (a+i). 4). 2. 6.4. Float brr[ ] = { 10. 11. 4. Cout << “max int =” << max (arr.5. } Void show( ) .2}. i<n . 6). For (i=1.3.

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

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

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

display( ). s. str). display ( ). } . S11. } Void main ( ) { String s1 = 20. 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. s). String s2 = 20. } Void string : : display ( ) { Cout << p <<end1. Note :For cascading of assignment operator it is necessary that return type must be string void string : : operator (string &s) { strcpy 9p. S2=s1. S1. ( eg ( string & s) ). x=s.{ Strcpy (p. resetstring ( “Welcome”). setstring ( “Hello User”). S1. } Void string : : resetstring (char *s) { Strcpy (p. display ( ). S1.p). S2. S2.x. Cout << “Memory deallocated”. } String : : string( ) { Delete [ ] p.

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. p). Float sal.e. Emp&). 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. Return (* this). Emp &). strudent &p). X= s. s. 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.String string : : operator = (string &s) { String (p. Char name [20]. Emp & p) { . Class Emp { Int age. Public: Friend istream & operator >> (istream 7. a programmer should overload the equal (=) operator & provide his own definition for copying the data pointer by pointer of source object rather than address. } Note :Q. Overloading Of Insertion And Extraction Operator Prototy Of << operator:Friend ostream & operator << (ostream & cout. 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. Istream & operator >> (istream & in. Friend ostream & operator << (ostream &.x.

In C++.sal.name<< “ “ << p. Equal Operator can never be overloaded as friend function. name & sal. Cout << “ Enter age.name. Q. float. char etc. It has to be overloaded as member function as friend function do not have any calling object .In >> P.sal >> P. Cin >> F. Now this violotes the regular symmetry of insertion operator and so it must be overloaded as friend function. Why don’t we overload insertion and extraction operator as member function? Ans:. } Void main( ) { Emp E.age << “ “ << P. Cout << E << end1. name and sal”.age >> P.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. Cin >> E. Emp &P) { Out << P. Return (in). Cout << F <<end1. } Ostream & operator << (ostream & out.Since equal operator should return the reference of calling object (to support coscading). F. Q. What is the need of overloading insertion and extraction operator? Ans:. Thus if it is done then wll would become P << cout where P is object af class. all primitive types like int. Return out. Cout << “Enter age. Q. 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. Ans:.

0. } Example User To Basic & Basic To User Class Meter { Float length. 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>). Public : Meter ( ) { Length = 0. 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. .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.

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

I= strlen (str).-. Conversion Routine In Source Object:Operator <destination_class-name> ( ) { //routines to convert source to destination Return ( <destination – object>). I . While (i>=0) { Sum = sum + (str [i] -48)* k K * = 10.} String( ) { Str [0]= ‘\0’. } 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. } Operator int( ) { K=1. Public: Radian ( ) { . } Conversion From User Defined To User Defined 1.

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

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

Radian R = D. Cin >> time. } }. R. Void main( ) { Degree D. .h> Class hour { Float time. } Operator float( ) { Float x = time * 3600. Return(x). } Assignment:#include <iostream. Public: Hour( ) { Time = 0. } Hour (double x) { Time =x/3600.{ Cout << “ Radian +” << rad. D. show( ).getData( ).0.show( ). } Void accept( ) { Cout << “enter time in hours”.h> #include <conio. } Void show( ) // Radian R (D). D.

Float x = t2. Cout << “when converted to sconds =” <<x.cin. } CONSOLE I/O OPERATIONS Unformatted 1. T2. Example :Void main ( ) { Formatted can be called by cin . accept( ).show( ).get( ). int num. Can read only characters Cin=cin. } }. int num).{ Cout << “in hour =” << time. Unformatted I/O (a) istream & get (char &) (b) int get( ) (c) istream & get (char *. Cout << “3600 when converted to hours=”.get(ch). Void main( ) { Hour t1=3600. int) Example :. T1. Hour t2. Istream & getline (char *. Istream & getline (char *. Getch( ).shjow( ). T2. char delimiter).

of integers given.getline (country. 20). nothing will happen on pressing enter rey. 20. Cin. capital [20]. } Getch( ). Cin. Cout << “its capital = “<< capital << end1. int) This will start from base add upto no. cin.get(ch). Example :Void main( ) { Char str[ ] = { “programming “}.getline (country. 20). } Note:cin. *) This will terminate after 19 character or on pressing *. While (ch ! =’\n’) { Cout << ch. Get (ch). Cout << “enter text and press enter to stop”.Char ch. Cin. . Cout << “enter capital”. } Void main ( ) { Char country [20]. Int I.20). Cout << “enter country name:”.getline (capital. Cin. Cout << “contry is “<< country << end1.put (str [i]). i<strlen (str).get (country. Functions Of Ostream Class (a) ostream & put (char) (b) ostream & write (char *. i++) { Cout. For (i=0.

By default the fulling is done using spaces. } For (i=strlen (str) . This fn is used for alignment. i++) { Cout. Int width (int) Old width aurrent width Void main( ) . i). specifies the no of values to be displayed after decimal pt specifies a character to be used to fill the unused area of field.write (str.write (str. i<=strlen(str). Cout << end1. Cout << end1. } For (i=1. Defining field Width Prototype:. } } 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. clears the flogs set using setf & restones the default settling. i). i--) { Cout. sets the format flag to be used while displaying the output. i>=1.int width( ) Returns the current width.Cout << end1.

{ 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

set conversion base to 10.void main ( ) { Int n. set the conversion field to 8 flushes the output screen Example :1. Cin >> a. Cout.no is = 64 Its hexaslccimal value = 40 0x 40 Example :.} Output  + * 4 2 0 . self (ios : : show base). 5 3 0 Formatting Data Using Manipulators Non Parameterised Manipulators Manipulator 1. Cout << “ no is = “ << n << end. Cout << “enter number”. bex 4. Cout << “ It’s hexadecimal value= “ << hex<<n. Void main ( ) { Cout << “ enter number”. WAP to read a number in decimal and display it in hxadecimal. oct 5. flush Description terminates the line and transfers the cursor to next row. Cout << a. Cin >> nex>> n. dec 3. } Output:. set the conversion field to 16. Cin a. . end1 2.

Cout << hex <<n << “ “ << dec <<n << end1. Float f = 122. Cout << setiosfloag (ios : : scientifie) << f << end1. setfil (char) 4. } Output:64 100 122. setiosflag (long) 6. setprecision (int) 3. Cout << hex << n << end1. 2 Overloading [ ] Operator . setw (int) 2. } Parameterised Manipulators Manipulator 1. Cout << setprecision (3). 343 0x0064 1. Cout << f << end1. 2 2 3 c + 0. Here possible value of int are 8. Cout << f << end1.Cout << “number= “ << n. Cout << setiosflag (ios : : internal } ios : : show base). sets the format flag. resets the format flag. 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. Example :Void main ( ) { Int n = 100.10 and 16.3434. setbase (int) 5.34339 9 122.

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

int). B1. // B2 = B1. operator ( ) (5. h. b. Cin >> l >> b >> h. show( 0. Temp. 3. int b. show( ). Box B2. } Void main ( ) { Box B1. Return (temp).h = h + this  h. 9). Temp. } GRAPHICS MODE PROGRAMMING Steps Required For Designing Graphics Mode Program . Public: Box operator ( ) (int.l = l + this  l. B1. B2. } Void show( ) { Cout << l. Temp. } }. << “ “ << b << “ “ << h. int h) { Box temp. Void get( ) { Cout << “enter l.get( ). int. 3.Class Box { Int l.b = b + this  b. Box Box : : Operator (int l. B2 = B1 (5. b and h”. 9).

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

returns the minimum value of if – coordinate. Ec = graphresult( ). Exit(1). “c:\\TC\\BGI”).Int getmaxx( ). & gm. “C:\\TC\\BGI”). Gd = DETECT. gm. 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. Exit(1). } Q. If (ec ! = grOk) { Printf ( “error”). If (ec!=grOk) { Printf ( “error”). ec. Void main ( ) { Char str[20] Int gd. Int getmaxy( ):Assignment:- returns the maximum value of x – coordinate. Restorecrtmode( ). &gm. Int b = getmaxy( ). Outtextry ( ( a/2). . Initgraph (&gd. “welcome to graphics”). Void main ( ) { Int gd. gm. Gd = DETECT. (b/2). Getch( ). Closegraph( ). ec. Ec=graphresult( ). } Cleardevice( ). Initgraph (&gd. Modify the above code so that now code display the Message at the necter of screen. Int a = getmaxx( ).

} 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

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

int rad) 4.setline style (4. int rad) 2. int rad) 3. in top. int right. int bottom) Filling Image With Different Patterns Void set color (int) Void setfillstyle (int pattern. intstangle. int bottom) 5. NORM-WIDTH). void rectangle (int left. int endangle. int right. int y. void bar (int left. Ox3333. void arc (int x. NORM-WIDTH) this will draw a dashed line. Drawing Arcs Or Circles Or Rectangles 1. Empty Fill 2. SOLID-FILL 3. int top. int endangle. int y. this will draw a solid line. void piesline (int x. int style) Pattern:The pattern parameter signifies the pattern in which filing is to be made. int y. LISLASH_FILE . setlinestyle (4. void circle (int x. OXFFFF. int stangle. LINE-FILE 4. value 0 1 2 3 Result Background color Solid Filling -------------------------- Name 1.

} Cleardevicl ( ). 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. Bottom=getmaxy( )/2. right. “SOLID-FILE”. CLOSED-DOT-FILE”}. Exit (1). top. Gd=DETECT Initgraph (&gd. Char * style [ ] = { “EMPTY-FILE”. Left = getmaxx( )/2-100. ----. Top=getmaxy( )/2-100 Right – getmaxx( )/2+100. . left. Also name of pattern should be displayed with in the rectangle. Void main ( ) { Int gd. I. bottom. Ec=grapgresult( ). ec.5. “C:\\TC\\BGI”). gm. &gm. If (ec !=0) { Printf (“error”). SLASH-FILL 6 BKLASH-FILE 7.

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

taking into consideration the pixels stored in memory & the pixels stores on screen. int y. int. int. int. int) 3. void *) 2. X = starting left coordinate Y = starting top coordinate Arr = maner un which color of the resultant pixel is to be decided. int option) void getimage (int. int iption) Copies or outputs the image pattern form memoery to the specified portion on the screen. void *. Cleardivice( ).Returns no. int. int). int imagesize (int.Outtextxy (x-50. Getch( ). Int image size (int. void * are. patter[i]). } Getch ( ). of bytes required to store the image. on any kind of error return -1 Void main ( ) { . int. int. } Storing and Drawing Images On Screen 1. 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. void putimage (int. Restorecrtdevice( ). int. int. int. y-50. int. void getline (int. int.

200. Ec = graphresult( ). Getch( ). Restore crtdevice( ). Line (200. 150. Char * buffer. msg [20]. If (ec ! =0) { Printf (“error”). 200). COPY-PUT). } VALUES COPY-PUT CREEN ON OFF EMORY ON ON OUTPUT ON ON . “Can not allocate memory”). buffer. Gecth( ). } Buffer = (char *) malloc (size-of-image * size of (char) ). Size-of-image = image size (150. Initgraph ( &gd. Close graph( ). Getch( ). 200. If (size-of-image = = -1) { Outtextxy (getmaxx( )/2. } Getimage (150. 220). 200. 220. 220. 200. 200). 150. getmaxy( )/2. Exit(1). Closegraph( ). Gd = DETECT. If (buffer = = NULL) { Outtextxy (getmaxx( )/2. “Error”). } Rectangle (150. buffer). “C:\\TC\\BGI”). ec. Exit (1). getmaxy( )/2. gm. 200.Int gd. Putimage (175. 150. Close graph( ). &gm. Exit(1). Int size -0f-image.

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 .