0% found this document useful (0 votes)
1K views178 pages

Naresh C++

Uploaded by

krish krishna
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
1K views178 pages

Naresh C++

Uploaded by

krish krishna
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 178
C++ Course Material Ni Granesto | technologies Opp. Satyam Theatre, Ameerpet, Hyderabad - 500 016. PAT TPE Naresh i Technologies Class Relationship “In heritance is the ability of one class to define the behavior and data structure of its instances as a superset of the definition of another class or class ...... inheritance also allows us to reuse o ot be receive tent every time” + Inheritance being a core concept of the object oriented paradigm, emerges in two bask contents © ABSTRACTION ABSTRACTION: + Recognize the constructs having something in common, * Create another construct that captures the commonality of all those constructs The above procedure avoids in dealing with the should aspect each time. Remove the commonalities from all the constructs of stop1 and restore them independently by letting them inherent from he construct created in step 2.. ‘> Hierarchica! abstractions of common features of contribute to the overall human understanding of the objects and classes compressing a system, REUSE AND SPECIALIZATION: 1. The use of inheritance a uses during needed construction. 2.__Before the construction of a class, recognize whether the desired features are already available or not. 3. If focused then establish a directed ink between the old existing class and the new class. 4, This new class is called specialized class and rescues all features of the old class. 5. Technically this application is called “programming by differences”. PROPERTY INHERITANCE: 4 Property inheritance is the foundation for inheritance at the design and implementation level. 4 The notion subject to inheritance in an analysis, a design and an implementation are respectively properties, computation and code. + Inanalysis phase the classes are not described though code, hence user has more abstract notion, Of inheritance. 4 Properties consist of declarative class features and associated constraints Property in heritance is @ relation between a sub class and a super class. C+ Programming, Naresh i Technologies CONSIDERATIONS : (Q->Sub class; P»Super class) ATTRIBUTES = Y + Ifall insStances of P possess attribute a, then so do all instances of Q. % All features and constraints applying to a in P also apply to a in Q RELATIONSHIPS : + Iithere is a relationship between P and class R, then a relationship exists between Qand * Takis lationship, is functional and all of P is in the domain of the relation ship, then for every instance q in Q there is an associated instance r in R. ‘TRANSITIONS : 2 + Oftthe behavior of P is described by a transition network with sate S and transition T, then Q has staie S and transition T as well. i INTERACTIONS : % [instances of P may interact with, accept even input data describing, and or generate ‘output event data describing instances of a class R, then so many instances of Q. SUBCLASSES : é 4 Itis more defensible to provide a reasoned justification of why the class is a subclass of the other. aq + Inheritance is justifiable when the sub class description imposes additional features and / i ‘or constraints without invalidating any properties described in the super class at 4 Itis possible to define sub classes justified by more than one’ application of the cases. FORMS OF INHERITANCE : ‘> SPECIALIZATION : The child class is a special case of the parent class; in other words, the child class is a subtype of the parent class. *e SPECIFICATION : The parent class defines behavior that is implemented in the child class but not in the (eb parent class. C++ Programming ay w uv ys ++ CONSTRUCTION : Naresh i Technologies The child class makes use of the behaviors provided by the parent class, but is not a subtype of the parent class. RALIZATION : The child class modifies or overrides some of the methods of the parent class, EXTENTION : The child class adds new functionality to the parent class, but does not change any inherited from the parent class. LAMINATION: ‘The child class restricts the use of some of the behavior inherited from the parent class. VARIANCE: ‘The child class and parent class are varianis of each other, and the class-sub class relationship is arbitrary. COMBINATION: The child class inherits features from more than one parent class. This is multiple inheritance. YOUR WAY FROM STRUCTURED PROGRAMMING : An individual statement is necessary (0 command the computer. The entire program is constructed over alist of instructions Applicable in areas where an organized principle or paradigm does not exist. Large-scale programming needs implementation though smaller collection of program units Program units are considered as functions or sub-societies or sub program or procedures. Every function should have a clearly defined purpose and clearly defined interface to explicit functions or programs. Funk ns collected in large scale are spelled as methods. C++ Programming Naresh i Technologies STRUCTURED PROGRAMMING PIT FALLS: Programs which are larges, protrude complexity Complexity costs the original schedule and economy emphasizes on doing things alone, Constitutes mostly on local variables, cut shorting the programs capability. * Programs modification needs modification to all the funct8ions accessing it % Function and data structure don't model the real world. + Does not contact the function for extensibility OBJECT ORIENTED MECHANISM : + The concept centralizes on keeping the data and the functions that operate on that data as asingle unit. —> The above specification is conceptualized as object. —> Data is hidden and hence safe from alteration. > Data encapsulation and data hiding are the objectives of oops. > Debugging and program maintenance becomes easier as interaction to member function is predefined. > Message is sent to objects using member functions, or methods. — Data items are referenced as instance variables. > Oops not only concentrate on details of program operation but also cheek the overall organizations of the program. BEHAVIORAL NECESSITIES OF OOPS : ~ EXISTENCE OF OBJECTS —> EXISTENCE OF CLASSES > EXISTENCE OF INHERITANCFE > EXISTENCE OF REUSABILITY >» EXISTENCE OF TOWARDS NEW DATA TYPES CREATION > POLYMORPHISM AND OVERLOADING REVISITING STRUCTURES UNIONS AND ENUMS IN‘ C. STRUCTURES: > Structure is a data type, which contains individual ciements that can defer in type. > Hence structure can contain integer, cher, float, double, etc., elements > Arrays, pointers and other structures, unions, enums can be included in structures. > Individual elements are referred to as members. C++ Programming Naresh i Technologies Defining Structures : > A stnicture being complicated than array shoufd be defined in terms of it members. Struct { Member 1; Meader 2; ‘Member n; > Struct is a key word, denotes the name of the structures > Member i, member 2, ......ete., are individual member declarations. > The individual members can be ordinary variables, arrays, pointers or other structures. + + ‘The member names within a structure should be distinct from one another, A member name can be the same as the name of variable that is defined outside the structure. > Once the composition of the structure has been defined individual structure type variables are déclared as struct varl, var2, ......Var N; PROCESSING A STRUCTURE : —> The members of a structure are usually processed individually as separate entities; Variable. Member —> Variable refers to the name of the struct type variable —> Member refers to the name of the member within the structure, ENUMERATIONS : It is a data type similar to a structure of a union. Its members are constants which are written as identifies The constants represent values, which can be assigned to corresponding enumeration. values. bod ‘Syntax: enum {mem, mem2,......, mem n}; —> Once variables have been declared as enumerated types they may be assigned values or compared to variables or values appropriate to this type. —> Internally, the acceptable values for each enumerated data type are ordered andl assigned sequential integer values beginning with ‘ 0 * (zero) > The equivalent numbers are required when inputting values using Scanf () or printing value-using printf 0. C¥ Programming # include # include void main( ) t enum color BLACK, WHITE, GREEN}; enum color x; printf ("\n %d, BLACK”, BLACK); printf ("\n %d. WHITE", WHITE); printf ("wn %ed, GREEN", GREEN), printf (“ta select a color !" ); scant ("%d", x); switch (x) { case BLACK: printf ("\n BLACK is selected"); break; case WHITE: printf ("ln WHITE is selected "); break; case GREEN: printf ("\n GREEN is selected"); break; } } #include void main() { enum string {LESS=0, EQUAL=0, GRATER=0}; char str1[80}, st12[80}; enum string emp; PHint€("\n enter first string:"); scant ("%s", strl); printf ("\n enter second string: scanf ("%s", st12); emp=stremp(strl,str2); if(emp < LESS) printf ("string 1 is less than string 2"); i€ (emp =EQUAL) printf ("stringl is equal to string2"); if (@mp > GRATER) printf (" string! & greater than string2"); Naresh i Technologies C++ Programming Naresh i Technologies # include # include void main( ) { enum BOOL (FALSE, TRUE}; enum BOOL b; char name[80], gend [8], drink[8}; printf ("\n enter your name : scanf("%s", name); printf ("\n enter gender : %d - Male %d-Femle",FALSE, TRUE); scanf ("%d"&b); switch (b) t case FALSE: strepy (gend, "Male"); break; case TRUE : strepy (gend, "Female"); break; printf ("\n while drink you like %d-cola, %d-pepsi :", FALSE,TRUE); seanf ("%d", &b); if (b = FALSE) strepy (drink, "Cola"); if(b== TRUE) strepy(drink, "Pepsi"; printf ("in Name: %s", name); printf ("\n Sex : %s", gend); printf ("\n Drink : %s", drink); } UNIONS : —> They are like structures, which contains members whose individual data types may differ fiom one another C —> Members within a union, all share the same storage area within the computer memory. > Unions conserve memory, Hence used in application involving multiple members > Values need not be assigned to all the members at any one time. > The bookkeeping required storing members whose data types are different, are handled automatically, C++ Programming Naresh i Technologies Ex: union { char key; int num; double price; 3 val; # include # include void main( ) ‘ union xyz { char a; inti; float £;}; sttuct def { char a; int § float £5}; xyzy; def d; printf ("wn STRUCTURE Address"); printf ("ws Address of a: You\n Address of [: % u\n Address of & %u",&d.i,8d.0); printf ("\n UNIGNS Addrsses"); prinif ("tn Address ofa: Yu \n Address of I: Yeu \n Address of & You'sey.a By, yf); y.a~' I yi=25 3.5 printf (" \n value of (char) a: %c \n value of (int) I: %d \n value of (float) f %f", ya, yi, 9.8); ysirQs y.0°3.5; y.an"T 5 printf ("\n value of (char) a: %c \n value of (int) I :%d \n value of (flosit) £: %6f", ya y.i, y.O5 y3.5; y.a=' y. print Cn value of (ehas)a:%e a value of (int) [:26d\n value of (float) f: %f", ya yiny.Ds # include # include # include union REGS i, 0; void showmouse( ) { ixaxals int6(0X33, &i, &C); void hidemouse( ) ix. ax=2; int86(0X33, &i, &0); C+ Programming Naresh i Technologies void main( ) { int gd, gm; gd-DETECT; initgraph (&gd, &gm, "C:\\TC\BGI"); while (1 Kbhit()) { + hidemouse( ); showmouse( ); Example-1 #¥ include struct employee c int nos char name [15]; float sal; h void main( ) { struct employee emp; printf (“\n enter the details of an employee:”); printf (“in employee no: ”); seanf('“%d", &emp.no); printf (“"\n employee name:”); scant (“%s”, &emp.name); printf (“\n employee salary :"); seanf (“%f", &emp.sal); printf (“in displaying the details of an employee :"); printf (“\n no: %d”, einp.no); printf (“\n name : %s”, emp.name) ; printf (“\n salary : %f", emp.sal); C++ Programming Naresh i Technologies Example-2 #include # define N2 typedef struct employee { int no; char name{15}; float sals void main( ) { employee emp{N]; employee accept_data( ); void display data (employee); inti; printf ("\n enter employee details : for (i=0; i typedef struct date { int d,m, ys typedef struct employee { int no; char name (15]; float sal; date dob; b define N 2 void main() { employee emp[N}; employee accept_data (); void display _data (employee) ; int find_employee (employee e{ ], int); inti; in enter the employee details +), emp {iJ=accept_data (); } jumps to accept _data () function definitions printf ("\n display the data"); for (i=0; i -1) { printf ("\n employee found ; displaying the dat display_data (emp, [pos]; printf (in enter new details :"); emp [pos] = accept_data ( ); , 7 C++ Programming Narech i Technologies printf ("\n not found "); return; } printf ("\n displaying the data after modification :"); for (10; i printf ("\n salary scant ("%f", &e.sal printf ("\n data of printh (dd-mm-yyyy) :"); scant ("%ed-%d-%d", &e.dob.d, &e.dob.m, &e.dob.y); return e; void display_data (employee e) i printf ("\n employee no : %d" , e.n0); printf ("vn employee name : %3", e.name); print? ("in employee salary -%f", e.sal), printf ("in data of birth ; %d-%d-%d", edob.d, e.dob.m, e.dob.y); return ; a C++ Programming Naresh i Technologies Example: enum department { finance, marketing, personnel }; typedef struct date { int d, m, y; }; union bit { int FALSE; int TRUE; }; typedef struct employee { 4 union bit delbit; int no; char name (15); department d; float sal; date dob; Bb #define N 2 #include void main( ) { employee emp[N];, employee accept data ); void display_data (employee); int find_employee (employee e[ }, int); printf ("\r, employee details :"); for (int iO; i-1) it printf ("\n employee found : disptay the data :"), display_data (emp (pos]); printf ("wn delete record [Y/N] : 2"); flush (stdin); chat ceply; scant ("%c", Sereply); if (reply =='Y’ || reply: emp [pos].delbit. TRUE else x printf ("\n not found."); return; y printf ("\n display the data after deletion :"); for (i=0; i Mt Variable 3 5) a a, + Cout is an object having simple interface % ‘<<’ is an operator called as the ‘insertion’ or ‘put’ operator input operator : cin cin is used to accept any information ints the memory location through standard input device. Syntax Diagrai cout Variable 4-cimis an object corresponding to the standard input stream. “> ‘>>’ is an operator called as the extraction or get from operator. # include void main( ) { int a, b; char name [10]; cout <<"\nillustzation of cout and cin’ ‘cout << "\n - cout << "\n enter any integer :"; cin>>a; cout <<"in enter any integer :*; cin>>b; cout <<"\n enter your good name cin>>name; cout << "\n\n displaying the data ... stay tune !" << name, cout << "inln value of integer cne :"< #include int a=5; char stz (10] void main( ) { celrscr(); char str [10] int a=6; (C+ Programming Naresh i Technologies Motock-L char str{ 10]= "every body"; int b=a; a=7; cout <<"\n inner block-2"; cout << “in b " cout <<"\na cout << "\n : a cout << "\n\n strings"; cout <<"\n- 7 cout << "\n content of global string { cout << "\p in inn..." <> cout << "\n value of global vfariable :"<<:: a; } } cout << "\n \n in inner-1 block"; cout <<"\na < There internally maintains a value 1 and false internally maintains ‘0° + Bools can be used in arithmetic and logical expressions the result of integer arithmetic applies through bool can be © back t0 bool. 4 Bool can be used as a return type of a function, OVERLOADING OF FUNCTIONS : ‘ Multiple functions can exist with same name, which is termed as function over loading. + Compiler detects the way of functional execution for the same by recognizing the argument within the functional call + Inorder to make a function handle a data type other than the specified, type casting has to be implemented. ‘Value = function name (data type) < variable name>); 4 Over loaded functions must at least differ in the type number or order of parameters they accept . 4 We should not rely on the return values to differentiate among them. +> A typed of merely gives another name Soran existing type and does not an original type of its.own. 4 Over loaded functions should not be created for doing different types of actions, + C++ has the ability to pass its own default argument within a functional call, if not represented. The default arguments are used if the calling function does not supply the azgument values when function is called. 4 The missing arguments should always be trailing arguments. 4 Default arguments are signed only in functions prototype and should not be repeated in the function definition, 4 ‘The compiler uses information from prototype of build a call. ADVANTAGES OF DEFAULT ARGUMENTS: 4 While making a function call, for such cases when arguments almost have same value, ‘Default arguments means that existing function calls can continue to use old number of arguments while a new function calls can use more, ‘ The default value for an argument can be a global constant a global variable or even a functional cal. CH Programming OPERATOR OVERLOADING : o ° * Naresh i Technologies Itis used to transform complex, obscure program listings into intuitively obvious ones, Over loading operators give an additional meaning for the regular arithmetical operators used. Operator overloading makes the programming logic more convenient to handle. Operator overloading is a concept where the C++ programmer can define his own operands. Operator over loading is achieved by declaring a function that defines the actions to be performed on the arguments passed to it. The operator overloading is declared using a keyword “operator” and then actual operator tobe declared, Operator overloading has extra edge when working with classes in C++. The following operators cannot be overloaded. and: . The operator functions have the’Same precedence as the intrinsic operations that use the same operator. Intrinsic operators defined by C++ cannot be redefined, INLINE FUNCTIONS : Funetions help in saving memory space, ‘Ateach plane where there’s a function would be inserted instead of a jump to the functio,:, which is termed as inline function. The inline functions eliminate the function calling ovethead of a traditional function, A function musi be declared to be inline before calling it. The code in inline function keeps the source file in a well organized way, as it is shown asa separate entity. a Void Pointers: # include # include void main () { void *x; char *s, ¢; inti, *}; float & cout <<“\n enter value for 0”; cin>> ¢; cout << “\n enter value for i” ; cin>> i; cout <<“‘n enter value for £2 ; cin>>f xi; /* assigning of integer ‘’ to Void pointer ‘x’ */ printf ( printf (*\n value of i %nx, address of L: Yu”, x, &i); %d”, i, *(int *)x); count of = C++ Programming x=; ?* assigning of char ‘c’ to void pointer ‘x’ */ printf (“\n content of x: You, address of C : %u", x, &c); printf (“\n value of ¢:= %c \t x == %c”, ©, *(char *)x), x-fi /* assigning of float ‘f to void pointer ‘x’ */ printf (“\n content of x : Yu, address of f: %u”, x, &f); printf (“\n value of f Mas J (int*)x;, printf (“in content of x: You, address of: %u", x, j )s printf (“in value of x: references = %d,\tj references %d”, *(int *)x, *)); REFERENCES: # include /ref-1 void main( ) { int k, 81 cout <<"\n enter any value for k:" ; cin>k; cout << "\n k is :="< struct insurance {int no; chat name [15]; float amt; }; void main( ) { void accept_data (struct insurance &); void display_data (struct insurance &); insurance x; cout << “\n enter insurance details :".; accept_data (x); cout <<“\n displaying the details :” ; display_data (x); } void accept_data (struct insurance &s) { cout <<“\n insurance no:” ; cin>> s.no; cout <<“"\n name :”; cin >> s.name; cout <<“"\n insurance amount :” ; cin >>s.amt; 3 void display. data (struct insurance &s) { ‘cout << “\n no:” < struct insurance k={200,"Ramesh", 3000}; struct insurance I= {300, "zarina", 5000}; void display_data (insurance &); voidmain() —_// Function Returning a Reference. { insurance & ref_fun( js void display data (insurance &); cout <"\n before calling ref_fun( ):" cout <<"\n contents of k:" ; Naresh i rechnologies C++ Programming Naresh i Technologies display_data (ky), cout <<"\n contents of i" ; display data (Qs ref_fun ()=I; cout << "\n after calling ref_fun()" ; cout << "\n contents of | display_data (k); cout <<" contents of | :” ; display_data(1); } insurance Seref_fun() { cout << "\n contents of k...calling in ref_fun()"; display_data (k); return (K); } Overloading of Functions: # include # include int add (int x, int y) { retum xty 5 } float add (int x, float y) { return x+y 5 ‘ 3 float add (float x, int y) { return x+y; } float add (float x, float y) 4 sehura x4} C++ Programming. 25 et 1B Naresh i Technologies void main() { int a b; float g, bs cout << "\n enter any two integers:" ; cin >>a>>b; cout << "\n a=" <-1) display_data (emp[k)s } Pmain*/ int findrecord (employee ef }, int n) for (int i=0; i # include struct string { char sir{20j; void print_string (string); string operator +(string, string); int operator — (string, string); void accept_string (string &); void main( ) { cout << "\n strings are equal :"; print_string(a); } C+ Programming, 28 cmatb; cout << "\n strings after concatenation :" print_string(c); 5 } main */ void accept_string (string &x) { cout <<"Wn enter any string 2"; cin >>x.str; } void print_string (string x) { } string operator + (string x, siting y) { cout << y.str ; Streat (x.str, y.str); return x; } int operator == (string x, string y) { ie(stromp (x.str, y.str)==0) return 1; else } Default Arguments: return 0; # include void main() { Aloat area (int, int, int fig=1)s inta, b, fig; cout <<"\n L.rectangte \n 2,square \n 3.cinele \n figure (1-2]:" 5 cin >>fig; 29 Naresh i Technologies CH Programming Naresh i Technologies 4 switch (fig) { > case 3: cout << "\n enter the dimensions of radius:"; , cin >>a; bel; 4 cout<< area (a,b,fig); break; case 2: cout << "\n enter the dimensions of side:" ; cin>>a; . ) bl; cout << area (a, b); break; case 1: cout<<"Enter the Dimentions of Length and Breadth :"; 7 cin>>a>>b; : cout< legal ~/ Float area {int a=5, int b, int fig); > illegal a Float area (int a~6, int b, int fig=2); > illegal ~“ Float area (int a=2, int b=2, int fig=1); > legal 2 a C+ Programming # include # include # include Hd lefine N 3 enum BOOL { FALSE, TRUE }; ‘typ { edef struct employee BOOL delbit ; int no; char name(15]; float sal, h voi { } id main () employee emp[N]; employee accept_data( ); void display_datalemployee), int find_employee (employee e{ J, int n); void list (employee { ], BOOL b=FALSE); BOOL Delete (employee { 1)s cout << "\n cout << "\n displaying the data:"; list (emp); if (Delete(emp)) { cout <<"\n displaying the deleted data : list (emp, TRUE): y else Tist (emp), employee accept_datac ) { employee e; e.delbit = FALSE; cout <<"tn employee no: "; cin>>eno; 31 Naresh i Technologies C¥+ Programming Naresh i Technologies cout << "\n employee name :" ; cin >>e.name; cout <<"\n employee salary :"; cin >> e.sal; return (¢); } void display_data (employee emp) u cout << "\n debit : "<< emp.delbit; cout << "\n employee no :"<< emp. no; cout << "\n employee name :" << emp. name; cout << "\n employee salary :"<>num; int pos = find_employee (emp, num); if (pos>-1) { cout <<"\n employee found : displaying the details"; display data (emp (pos); 2 CH Programming cout << "\n delete the record : [Y/N]:"; char reply cin >> repl if (reply =="Y' || reply ='y') , emp(pos}. delbit=TRUE; return TRUE; } else cout << "\n not found"; return FALSE; } INLINE FUNCTION! # include inline int check, equality (int x, int y) { fO=y) return 1; else return 0; 3 inline void cube (int x) fe Coil << xxx; } void main( ) i inta,b; cout <<"\n enter any two integers :"; cin >>a>>b; if (check_equality (a, b) ) cout << "\n equal”; else cout << "\n not equal”; cout <<"\n cube of a: "; ‘cube (a); cout <<"\n cube of b :"s cube (b); 3 C++ Programming. , CLASS * it isa way to bind the data and its associated function together it helps in hiding the data and functions from external use a class is considered as an abstract data type (A.D.T) which reflects its q data type + every class definition consists of two parts + class declaration © class function definition , class declaration describes the type and scope of its members * class function definitions describe, the way the class function are implemented Has a built in DECLARATIVE SYNTAX : 3 Syntax J: a lass class_name : { i Jd member variable declarations; methods declarations / definitions, J h Syntax 2: 3 ey hip g 27k . élass class’ name ‘ . =] (a private: i 2 ‘member variable deélarations methods declarations / definitions; a h : Syntax 3: i class class_name { public: members variable declarations; ° methods dectarations / definitions; ; h Syntax 4: > class class_name “ { protected: i ‘member variable declarations, i methods declarations / definitions ; ~ h C++ Programming 34 : Naresh i Technologies Syntax 5: class class_name Co , private: member variable declarations; methods declarations / definitions, public: member variable declarations; methods declarations / definitions; protected: ° member variable declarations; methods declarations / definitions; b POINTS TO PONDER + + * * * + ¢ + * A class declaration is similar to a structure declaration The key class instructs the compiler that the information is abstract data type class name, ‘The class body should be enclosed in brakes and should be terminated using semi-colon @) The class body bears variable and methods declaration, which collectively called as, smbers, The members are usually grouped under which one followed by colon (:) Private members can be accessed only from within the class Private class completely hides the information, and does not provide feasilibility of accessing member's vafiables outside its environment. The binding of data and functions together into a single class type variable is referenced as encapsulation ”, bility labels called ‘private’ & ‘public’, PRIVATE AREA PUBLIC AREA CH Programming 7) Naresh i Technologies ATTRIBUTES : 2 + Real life entities are often described with words that indicate stable features. ‘A feature may be seefi as a binary relation between a class and a certain domain Ex: eye {brown, blue, yellow, green, red }; % The applicability of certain features may change overtime + A class is characterized by its set of defining features or attributes. + Attributes are employed to describe an instance of a class. OBJECT : % Anobject is an entity that may have a physical boundary ‘The characteristics of objects are 7 * State = Behavior « Identity % Itis a conceptual entity that can be identifiable +> Has features that Spam a local status space * Has operations that can change the status of the system locally METHODS : % - An operation is an event-driven transition or called method, identified by its associated input event name and signature. + A method can be unit-directional or hi-directional operation guaranteeing to reply to its sender. 2 4 An object that receives the message is called receiver, the set of actions taken by the receiver constitute methods. INSTANCE : If the object is a member of a class then it is called as an instance. ABSTRACTION = “ An abstraction devotes the essential characteristics of an object that distinguishes it from all other kinds of objects and there provides crisply defined.conceptual-boundaries, relative to the perspective of the viewer” > Grady Booch ‘Abstracting the internal working of a data type is not complete unless the data and the set of methods that operate on it are mode transparent to the user. “C+ provides this feasibility by including operations related to data type within the structure or class declaration itself. 7 C¥+ Programming Naresh i Technologies ABSTRACT DATA TYPE : *% The outcome of abstracting the internal implementations of a user defined data type, with. the use of access specifies is called as ADT. 5 ENCAPSULATION : , + Objects in design contain features that support advertised functionality, but hide the underlying mechanisms so that, other objects cannot reach and corrupt them. “It is process of hiding all of the details of an object that do not contribute to its essential characteristics” ~> Grady Booch Example 1 : . # include ) # include 7 class chair >.: if at public : } int height; int no_legs; chi type_material [15}; char color [15]; void get_data() is eo t _ cout <<“\n enter height of the chair 2”; : ined cin>> height; cout << “\n enter no. of legs :” ; cin >> no_legs; cout << “tn enter type of material >; cin>>type_material ; : cout << “\n enter color :” ; : cin>>color; Z ) 3: void show_data () { cout <<“ height of chair: > reply; } while (reply= = ‘y’ || reply YY"); cout <<“\n height:” Hinclude class student { int no; char name[15]; public : void show _data( ) { cout << "\n student no :" << no; cout << "\n student name :" <>no; C¥+ Programming 38 Naresh i Technologies cout <<"\n student name : cin >>name; 3 B void main( ) { student 5; cout << "\n enter student data"; clrser( ); s.get_data( ); ‘cout << "\n displaying the data:\n" ; s.show_data( ); } Syntax for defining the methods outside the class : Class : member variables; retum _type return_type b return_type : { J returm_type : member_function! (void/arg); member function? (void/arg): :member_funetionl (void /arg) : membr_function 2 (void /arg) Function “F 39. C++ Programming Naresh nologies Uustration For Defining The Methods Outside The Class And Array Of Objects : #include #finclude # define N2 class insurance { int no; char name[15); float amt; public: void accept_data( ); void show data}; ‘Function - Declaration f method prototype h void insurance : { cout << “\n enter insurance no :” ; cin>>no; cout >name; cout <<“\n enter policy amount"; cin >>amt; return; __| ) { void insurance : : show_data() —_——-+» Funetion Definition, { cout << “\n insurance no 2" < } } = i CONSTRUCTORS : > ‘Iisa special member function whose task is to initialize the objects of its class. ees % The name of the constructor is the same as clas_name. + A constructor gets invoked whenever an object of its associate class is created * Aconstructor gets its name since it helps in constructing the values of data members of the class. Declaration Syntax. + Syntax: 1 ‘Class i: 7 2 (void/arguments) 2) t Any executable / initialization statements, ) : ) iy S Syntax :2 Class aN { 3 : member variables ; member functions 5 (void/arguments) h : : (void / arguments) { . Any executable / initialization statements; i } ) Z C++ Programming 7 Naresh i Technologies os ‘An object initialization is guaranteed to be autotnatic, whenever a class contains a constructor. ‘There is no need to write any explicit statement to involve the constructor function Constructor without parameters are considered as default constructor ee -. CHECK LIST FOR CONSTRUCTORS : Declaration should be restricted to public section. Objects creation is a guarantee for constructors invocation Constructors do not have return types, hence cannot return values Constructors cannot be inherited, but explicitly a derived class can call the base class constructor. Constructors can processes default arguments. Virtual constructors are not possible Referring to the addresses of constructors is not possible An object with a constructor cannct be used as a member of a uaion, Constructors make implicit calls to the operators new and delete when memory ailocation is required. ‘When a constructor is declared for a class, initialization of the class objects become mandatory. wee Sooo ° PARAMETRIC CONSTRUCTORS : ‘Helpful to initialize the various data elements of different objects with different values ae when they:are called. © In C++ arguments.can be passed to constmctor function when objects are crated. 3 % Constructors capable of acceptance arguments are called parameterized constructors. ) Declarative Syntax -: : ) Class i 5 variablel, variable2, : ) (argl, arg2...); ) bo 3 : : < class_name> (argl, arg2...); ( : + variable initialization / assignment; f 3 } 2 = D Co Programming 42 INaresn | technologies + In parameterized constructor when an object is declared the initial values should be ( passed as arguments to the constructs function. # By explicit call to the constructor + By implicit call to the constructor & Parametetized constructors should be provided by appropriate arguments Paramoters to 2 constructor cam be of any type except the class to which it belongs ‘A constructor accepts a reference to its own class as a parameter CONSTRUCTOR OVERLOADING : 4A constructor can supply the data values by itself without depending on the calling program. ‘A constructor some times may depend on the data vaiues to be supplied through If more then one constructor function is defined is a class then we call. that the constructor is overloaded. C++ has an implicit constructor, which creates objects, even through if it is not defined in the class. ¥ “> + Iris always better to define « “do-nothing” implicit constructor. in) ee DEFAULT ARGUMENTS IN CONSTRUCTOR : (51) } “fan argument within a constructor is initialized at the time of signature, then it is called ce) as default drgurrient consteucvor. + The actual parameter, if specified over sides the default value in the constructor. 5 @ ‘The default argumentts should always be maintained as trailing argumenis. OBJECTS DYNAMIC INITIALIZATION : (57) ‘The initial value of an object can be provided during seen time Dynamic initialization provides various initialization formats, through overloaded y constructors. : + This increases flexibility of using different formats of data at runtime, with respect to a situation. “When constructors are overloaded, the parameter matching:the:input-valueis involved. + COPY CONSTRUCTORS : 4 Accopy constructor is used to declare and initialize an object from enother object. 4 A copy constructor takes a reference to an object of the same class as itself as an argument, ‘ 4 Ina copy constructor an argument should not be passed by a value. 4 Ino copy constructor is defined, the compiler supplies its own copy constructor. i - C¥+ Programming Naresh i Technologies DYNAMIC CONSTRUCTORS : (59) * Constructors can help in allocating required memory while object creation. The above application helps in allocating right amount of memory for each object, when size differs Memory allocation to objects exactly at the time of their construction is called as dynamic construction of objects Dynamic constructors are conceptualized using the ‘new’ operator. DESTRUCTORS : (54) * bos ¢ oe * It is used to destruct the objects created by the constructor A destructor is also a member function, whose name is same as class name, A destructor name is preceded by a tilde ‘ ~” A destructor does not accept any arguments nor it returris any values. Destructors are invoked implicitly by the compiler upon the termination of the program Destructors are cleaning agents, saving the storage space, which is not in use. The ‘delete’ operator is used to free the memory occupied by the constructor The explicit usage of delete operator is used in all such cases when a pointer to an object ‘goes out of scope. Objects are destroyed in the reverse order of creation NEW and DELETE OPERATORS : _ (55). o Fe & oe ‘The:tnew? opgtator allocates memory, from free store performing the job of mailoc 0; The ‘new’ operator, when.used with the pointer.to a data type, a structure or af array allocates memory for the item and assigns the address of that memory to the pointer, Dynamic allocation techniques should be used when it ywn in advance how rauch of memory space is needed. The ‘delete’ operator is used to free the memory allocated by the ‘new’ operator. ‘These operators customize the lifetime of the object clearly under the control of the programmer. The ‘new’ operator can be used to crate objects of any type. Syntax : Pointer_var = new data type; Pointer_var = new data type(value}; Pointer_var ~ new data type(size); u“ C+ Programming * Naresh i Technolagies: When a data object is no longer necessary it should be destroyed. Syntax : delete pointer_variable; delete {size] pointes_variable; POINTES TO PONDER : oe votes be ‘New’ not only allocates memory but also creates an object by calling its constructor. ‘Delete’ not only deal locates memory, but also.destroys the object by calling the objects destructor. ‘New’ allocates memory from heap, called as “free store’. ‘Memory allocated using new{ ], miust be deal located using delete [ ]: An object erated using new exists until itis explicitly destroyed using delete. A delete operator may be applied only to a pointer returned by new or zero. “The delete when applied onto an expression does nat delete the pointer alone, but the object being poitited to by the poititer: To reallocate any memory copy costrotbr should be used vather than tenew() 0 operator, The new operator has following benefits It erates an object % Itis type safe, rctuming pointer of appropriate type. + Can be overloaded class_by_class basis. Never try to delete's potiniér viviee, becalisé tier’ is a chaiiée of comipting the heap. Nopdeletion ofan object isnot an error, but itis always better to delete the object once its Purpose is over. Illustration of Default Constructors : # include # include C+ Programming Naresh i Technologies void show( ) cout << “An (x,y) : (S<>x; cout << “\n y-coordinate .” ; cin>>y; } h void main( ) ° t clrser (5 point a, b; cout << “\n showing details of object 1”; ashow( ); cout <<“"\n showing details of object 2”; b.show( ); cout <<"\n enter values for coordinates of object 1:"; 2. get )5 cout << “\n enter values for coordinates of object 2:"; b. get()s cout << “"\n sharing coordinates values for object 1:"; a. show();, cout << “in showing coordinates vaiue for object 2:°5 . show( ); 3 # include # include int count=0; class xyz t int float public: xyz() { cout <<“‘\n \n object no: " <<++count; cout <<“\n called from constructor :”; cout << “\n initializing the variables i=10; f5.2; getch( ); Soper a C¥+ Programming void show () { cout << “\n \n value of integer ** # include class point t. int x, ¥s public: point (int a, int b) void show( ) { gotoxy(y, x); cout << (Ky) : OMEERE” MCG? 5 3 } void main) t celrser( ); point a(10, 10); a. show( ); ‘char reply = *y"s 47 Naresh i Technologies C++ Programming, intr, ¢; cout <<“\n enter new position (r,¢) :”; cin>>r>>c; point B(r, c); b.show(), , 5 cout <<"\n wanna continue [Y2N]? :”; ‘y’ UL reply= = ‘Y"); Mlustration of Constructor Overloading : # include # include class emp { . int aos char name [15}; char address [50]; float sal; public: emp() sal=2000; } accept_data (); emp (float s); void display( ); void print_pay_slip( ); void accept_data (int flag); ie void emp :: print_pay_slip() { cout << “\n no \t name \t \t\t salary \t HRA \t net salary" ; cout<<"\n float hra= sal*0.15 Naresh j Technologies cout << no <<"\t" <>no; cout << "\n enter name :" ; cin>>name; cout <<"\n enter address :" 5 cin>>address; if ag) { cout <<"\n salary :" <>sal; 3 getch(); print_pay_stipO); display( ); retum ; B void emp =: display() { ccut << "\n no: "<>ans; 7 C++ Programming Naresh i Technologies if(ans) : { cout << "\n enter the salary :" ; float salary; cin >> salary; emp x(salary); 2 else { emp x; } cout <<"\n wanna continue [y/n] cin>>reply; } while (reply== 'y || reply=="Y); } IMlustration of Default Arguments in Constructors : #include # include #include . class Bank SB « { private: u int ace_no; 7 char name (15); £ float amt ; Ze Default Argument public: ‘ Bank_SB (int AC=1000); - void accept ( ); : void show( ); b ‘ Bank_SB :: Bank_SB (int AC) { © if (AC<500) ‘ ‘ cout << "\n minimum balance shoutd be 500 !" ; exit(1); © } else ¢ { amt=AC; - accept( ); } ‘ } 50 C++ Programming void Bank_SB :: accept( ) { 3 cout << "\n enter the account no :"; cin>>ace_no; cout <<"\n enter the name of person :" ; cin >>name; cout << "\n amount to be deposited :" <>amount ; Bank_SB objSB (amouzt ); objSB.show( ); cout << "\n wanna continue [y/n] 2" ; cin >> reply; } while (reply= '’ || reply ='Y'); cout <<"\n calling without inserting the amount” ; Bank_SB obj1; obj. show( ); n Calling with Default Argument Naresh i Technologies (C+ Programming Naresh i Technologies Iitustration Of Copy Constructor : # Anclude # include class point { private : int x, yz public : : point (int a, int b) ° ( x2 (a>25) 2 25a; y=(b>80) ? 80 : b; , point { ) void show( ) 1 cout << "\n displaying from the specified position o gotoxy (y, x): cout << Mix, yt (recece™ , “ecyec™y™ 7 iy void main( } ‘ : ‘ elrser( ); char reply; point a(15, 30); a. show( )7 do G ‘ cout << "\n one way of copy constructors : int x, ye cout << "\n enter row and col, positions :"; : cin>>x>>ys e point bix, y): point ¢ = br . i cout << "\n from c : ce. show( 7 cout << "\n form b b. show( ); y while (reply=='y! 11 replys='¥")3 iE . cout << "\n second way of copy constructor” ; : c point b; bea: : b. show Js H - = C++ Programming, Naresh i Technologies Mlustration of Destructors : : # include # include int count =0; class destroy ) { * int rank; int i; float f 5 public : destroy() { rank = -++count; cout << “\n \n rank of the object is.” << rank; - cout << “\n constructor called cout << “\n initializing the attributes :” ; ee ; getch( ); di } ~ destroy() J cout <<“ \n rank of the object :” <"; 3 getch( );, 3 ‘void show() > t : cout <<“\n \n value of integer :” # include class string { private: char *str; int len; publ string ( ); string ( char* ); ~ string (); void show (); } string : : ~ string () { cout << “\n destructor called...” ; delete str; } string : : string () t len=0; str=new char [len+1] ; } string :: string (char *s) cout << “\n parametric constructor called. len=strlen(s); str=new char [len+t] ; strepy (str, 8): 3 void string : : show( ) { cout <<“in string : ” < {. cout <<“\n enter your good name :” ; cin>>s; string s_obj1(s); sting s_obj2 s_obj3 = s_objl; 8_objl. show( ); s_obj2. show( }; s_obj3. show( ); cout <<“\n continue [y/n] ?:” ; cin >>reply; } while (reply= s_obj3. show( ); 5 obj; "| Lreply= =") : Dynantic Object Creation: fincludeciostream.h> #include class point { private : int x, public : 5 point (17 point {int, int); 2 ~ point (7 woid show (1; point :: point ( ) gat) c'ets cout << "\n default constructor calld." ; point +: ~point( ) cout << "\a Destructor is called." ; point :: point (int a, int b) (a>25) 2 25: ae i <= (ne80) 2 ad: be cout << "\n parametric constructor called” ; O ss C+ Programming Naresh i Technologies a : es = void point :: show ( ) t 5 aeloa See 2 cout << "ir, c) : ("Kerce™, "<>a>>b; penew point (a, b); a cout << "\n calling show( ) of p : press any key : "; getch( ); - po>show( 7 : cout << "\n destroying the p : press any key : "; getch( 1; co delete ps cout << "\n creating another object \n re-eutu row, col :" 7 Gin >>a>>b; point * x7 clrset( ); c xenew point (a, b); cout << "\n calling show of x: press any key. getch( )7 x ~>show ( }; getch( }+ r elesez( }5 cout << "\n calling show of p after show of x press any key : “> geteh( )7 p»>show( )7 cout << "\n destroying the x : press any key ° gateh( 7 delete’x + cout << "\n calling show of x after delete of x press any key" ; geten( ); elrser( }; i a x->show (7 Dynamic Initialization of Constructors: # includeciostream.h> a oa # include # include class string » ( private: char tstz; int len, num; (C++ Programming Naresh |! =chnologies public: string( )s string (.char *); 7 void accept ( | void show( ) void concatenate (string, string); 1h stying :: string (} { cout << "\n default constructor called Len; strenew char(lentl]; ’ stving :: { string (char *s) cout << "\n parametric constructor called. : len=strlen(s) ; i str=new char (lentl]; strepy (str, 3)7 void string +: accépt( ) ‘ 0 5 cout >s; mestring (siz m.show( }3 cout << "\n continue .(y/a] 22" 4 ‘ aes cin >>replys dynamic constructor for m" ; ¢ }uhile (.reply== ‘y , c ~ THIS POINTER : (64) 5 2 + This is a reserved keyword to represent an object that invokes a member.function. £ % ‘This is a pointer that pointer to the object for which ‘this® function was called. “© When using ‘this’, the starting address is the same as the address of the first variable in : the class structure. + This unique pointer is automatica'ly passed to 2 member function when it is called, (me ‘The ‘this’ pointer acts as an implieit argument to all the member funetions. + The ‘this’ pointer is used implicitly when overloading the operators using member's functions. ‘The important application of ‘this’ pointer is to return the object it points to e 4 The ‘this’ pointer is used in such cases when two or more objects inside a member functions should be compared and should return the invoking object as a result. = ‘Using this pointer any member function can find cut the address of the object to which it L is a member. C++ Programmit 58 gramming Naresh i Technoiogies STATE DATA MEMBERS : (67) A data member of a class can be qualified as static + The characteristic properties: - % Itis initialized to zero when the first object of its class is crated + No other initialization is permitted. + Only one copy of those members is crated for the entire class and is shared by all the objects of the class, no matter how many objects are crated, © Itis visible only within the class, bu its lifetime is the entire program. % Static variables are normally used to maintain values common to the entire class. + The scope of each static member variable must be defined outside the class definition. The static data members are stored separately rather than as part of an object. + Since these variables are associated with the class rather than the object, they can be called as class variables. STATIC MEMBER FUNCTION : % The properties of static member functions: “A static function can have access to only other static members declared in the same class, ‘The class name can be used to calll a static member function. Class_name:: function_name; THE CONST QUALIFIER : (70) ‘The keyword const proceeding the data type of a variable specifies that the value of the variable will not change throughout the program. + Const ensures that the alteration to the value within the variable is not possible. % Const is a better idea when compared to macros as the scope of the variable and its operation can be controlled. ‘The Const Member Functions : (74) © Aconstant member function guarantees that if-will never modify-any.of its.class’s member data, “Ita function is declared inside the class but defined outside it, then it is recessary to use const is declaration as well as definition. ‘The const member function arguments: $ Itisused in such cases when an argument passed to an ordinary function by reference should not get modified. “© Only coust member functions can be used with constant const objects. 50 (C+ Programming 4 include # include class THIS int nz public THIS () ( cout << "\n object crated at the "<>a; THIS obj(a); obj. showdata( ); cout << "\n continue [Y/N] 22" 7 cin>>reply; J while (replye= 'y' || repli "r # include # include # include class string ( char * str; int len; public \ steing ()+ string (char *); void show( 17 void append (string & x); * str 7 cout << "\t length with this :." len ; return; void string +: { append (string ex) char *temp; ‘tempenew char (Lenetls temp=stry lensthis~zlen + x.len 7 this->strenew char (Lentil; stropy (this->str, temp); streat(this->str, x.str) + return; a void main( ) { string st, 52, s3; char *s, reply? elrser()7 do ( cout << "\n enter year first name: "; eier>s: sl=string(s) ; cout<< "\n enter year second name : \n" ; s2=string(s); cout << "\n appending the second string to the first string si. append (e715 sl. show( 1; cout << "\n continue [¥/N] 25" cinm>reply: } while (reply== 'y' |) replys= 'Y*); 6 C+ Programming a Naresh i Technologies WStatic-1N/ # include # include # include class student, ( private : static int no; char name(15]; a (C++ Programming _ Naresh i Technologies public student () { } student (int); void get_data( ); void show datat }+ " student :+ student ( int num) 1 no = num ; ) void student 1 show data) cout << “\n student no :" <nante? y At student : void main( ) { int 9; chaz reply; cour<< "\n enter the last student number :* cin>ony student $(n); do t clrser( }7 student k ; cout << "\n student data." ; k. get_data( ); cout << “\n \n displaying the data." ; k. show data( ); cout <<"\n continuety/n) ? cin >>reply; } while (reply== Vy veplyes 135 @ (C+ Programming Naresh i Technolagies Illustration of Constants: # include 4 define N 10 void main( ) ( const int max=100; int add_series (int); printf {"\n the global constant is (# define N) : %d and is available to all the functions", N)7 printf ("\n the main( ) constant (const max) : td is available only with the main( )" , max); printf ("\n \n enter any number :" ) seanf ("$d", &m) 7 sum = add_series (m); printf ("\n the constant in add series( ) cannot be accessedfrom here or fzom any other functon"); printf ("\n sum of the series : td", sum); int add_series(int n} int i,-total=0; const char *str = “cyber vision"; printf ("\n calling from the function add series ( )."); printf ("\n the global constant (# define N) is available here : 8d", N); printf ("\n the main( ) constant (const max} is not available"); for (1=0; i void main( ) void append (char*, const char*); char str1(30}, stx2{15]; printf ("\n enter your first nane scanf ("8s", strl); printf ( "\n enter your last nane : scanf ("8s") str2); printf ("\n calling the append function append (str1, str2); printf ("\n after appending. \n string are : printf ("\n stengl : @s \t string? : 8", strl, str2i7 C+ Programming Naresh 1 Technologies void append (char ‘d, const char ‘s) t+ "Nor; att); "NOt; set, dee) # include void main( ) t void check_odd (const int *); int num; printf (“\n enter any number to check for od scanf (“%d”, Senum); cheek_odd (& num); } void check_odd (const int *x) { inty; y=*x%2; if==0) printf (“in not odd”); else print? (“in odd”); Illustration of functions returning constant values 4 include void main( ) t const char * concate ( const char‘, const char*); char fname[15], 1name[15]; const char *fullname; printf ( "\n enter the first name scant ("$s", fname); printf ("\n enter the last name :"); nf (" Bs", Lname) ; fullname = concate (fname, Lname); printf ("\n first name : 8s \t last name : $s \t = \t $s", fname, Iname, fullname) ; ) "7 a C++ Programming Naresh i Technologies const char *concate (const char *f, const char ¥1) ( char *£ull int i, 7 for (ie0; ELA]!= '\o" 7 tHe) fullli] = £(4); for (4-07 1[j]!= '\o' 7 jt, i++) full (4) = LCi; full (41 = ‘\o! printf ("\n full : ts", full); return full ; IMlustration of const member functions and constant objects : #include #include mt class CONST t . private : int x, ys public = Ses CONST () ( - wel : , Const (int a, int b) ‘ t in 1 void: show! ) S EF i gotoxy( yy x07 Sout << Mixy) (Meee, Meeyeen)# 7 : o i e vold change_position ( ) i cout <é "\n enter new row, col :"; cin>aoy 3 oe ; void change_location( ) conat ' { cout << "\n enter new row, col :¥ 7 cins>s>>y; oa Zi ya3i// Assignment is not allowed y ‘C++ Programming 6 er 1B ° Fe ore eerie void main( ) t = sclescr (); const kz é keshow () 2 int ro; cout<< "\n enter row, col positions :" 7 ein>>r>>e7 SONSTir, chi 3 k.show()7 klchange position (); > k-show ()7 > k change location() kK. show . cout << "\n illustration of constant object : "7; — ° const CONST 1; Le show): cout << "\n enter row, col position :” 7 ein>>2>>¢; 1 = CORST(r, 2); //not allowed 1. show( 37 _ ) ) 1 references — cont 3 # include y void main( ) c int m, m4; } const int &k=m; ’ printé (“in enter any value for m ~ scanf (“%d”, &m) ; a printf (“in value of m: %d, k: %d”, m, k) ; Te 5 printf (“\n enter any value for k a scant (“%d”, 8k); 7 printf (“\n values of m : %d, k : %d”, m, k); <1 i 1k=1 or k=variable } aot allowed m4; 7 CH Programming 7 Naresh i Technologies INHERITANCE INHERITANCE : + + Itis a process of crating new classes called derived classes, from the existing classes. + The existing classes are called as base classes ‘The derived class inherits all the capabilities of the base class + The derived class can add its own new features and refinements of its own. + Thenew features applied onto the derived class keeps base class unchanged. ‘Inheritance permits code reusability. + The base classes once written and debugged need not be touched once again, but can be ‘¢ adapted to work in different situations. % Inheritance not only helps in reusability saver tirae and money increases reliability % The code reusability feature introduces the concept of crating custom classes. DEFINING DERIVED CLASS =: ‘A derived class is defined by specifying its relationship with the base class, in addition to its own details. Syntax: Class derived_class_name : visit € ity_mode base_class_name : member 1; member 2; f) member 3; B A 4 The coion separator indicates the compiler from where the base class has been derived. +b The visibility mode is optional and by default private i “Visibility mode specifies the exact features of the base class whether they are derived o privately or publicly 4 When base class is inherited privately > Public members of the base class beoume:privatermember of the darived class > The public members of the base class can be accessed by member functicns of the derived class. > The members of the base class are inaccessible to the ohjects of the derived class + Its own objects using the dot operators can access a public member of a class. ‘When the base class is inherited publicly. > Public members of the base class become public members of the derived class. ¢ —> Public members of the base class are accessible to the objects of the derived class. a + Inboth of the above cases, the private members can’t be inherited at any cost. 4 Inheritance helps in implementing the concept of incremental paradigm. a C++ Programming !Naresn | tecnnologies POINTER TO PONDER : ‘ Pottered members behave just like private members until a new class is derived from the base class that has protected members. * Ifa base class has private members, those members are not accessible to the derived class protected members are public to derived classes but private to the remaining program (ex: objects) 5 ‘A derived class can specify that a base class is public, or private by using a notation in the declaration of the derived classes. 5 Sentax: ~ Class : public < base_class_name>, Class : private ‘The public access specifier specifies that > Protected members of the base class are protected members of the derived class > Public members of the base class are public members of the derived class "4 + The private access specifies specifies that Dt ~» The protected and public members of the base class are private members of the derived class : ~> The default access specifies is private When an object of a derived class is defined 3 —> The compiler executes the constructor function of the base class fallowed by the constructor function af the derived class —> The parameters list for the derived class constructor function may be differed from } that of the base class’s constructor function —> The constructor function for the derived class must tell the compiler what values to ) use as arguments to the constructor function for the base chiss + lf thebase class and the derived class have public members finetions of the same name and parameters list types, then the function in the derived-class gets a priority when the function is called as a member of the derived class object 4 a program can declare objects of the both the base and derived classes , the two objects , the two objects ase indeperdent of one another a C++ Programming Memory Representation Class base { . Private: members, public: members; b class derived : private base { private: members; public: members; Naresh i Technologies — a S _ Class base [eta dive Private: se Members; Members of derived; Public: Members; Public members of b: Publie: Members of derived; + Here the private members ave not visible to the derived class + The public members of the base class become as private members of the derived class. Class derived : public base ic private: Members of derived; public: "Members of derived; yy 70 CH Programming Naresh 1 Technologies PUBLIC Class base Class derived Private: Private: Public: Members; Public members of base class Public Members of derived; —> Here the private members are not visible to derived class » The public members of the base class will become public member of the derived class Class base ( 5 private: members; . protected: members; public: members; ‘ Llustration of Inheritance : Hincludeciostream-h> class one ‘ ! 5 int num; , public: void accept_data() ( cout<<"\n enter any number + return; ) void show_data() ( cout<<"\n the number is :"<>name; return7 ~ y void show_data() t one: :show_data()i cout<<"\n Your name :"< Hneludectostream.n> Hacludeceonioch> {> cass base : i on public: is base() i ( i ~ cout<<"\n Derived 1 class constructor called getcn)? : 4 ) ¢ ‘base () cout<<"\n Base class Destructor called getch(); a 7 C++ Programming Naresh 1 lechnologies class dl : public pase ‘ public: ay t cout<<"\n Derived 1 class constructor called . 5 getcn(); ) a0 a cout<<"\n Derived 1 class Destructor called . getch (7 ) Me void main() 4 21 ob}: ) class derived : public base a { a oe private: members : public: members; b Ee 5 ) PUBLIC. : Class base Class derived A Private: ae Members of derived: i “Public members of base class 1 Public Members of derived; Protected: Protected members of base class Protected Members of derived (if any); Members; a C++ Programming Naresh i Technologies —> Here the protected members of the base class are visible to derived class as protected members > Ifthe derived class is privately derived, the protected members also behave in same manner and visible to the protected —> But the protected members are not visible to the objects of that class, #include #include #inelude class point ‘ protected: int x, public: point () i} point (int x, int c) ( assign_x (x); assign_y(c); y void draw(); void assign_x(int); void assign_y(int); int show.807 int show y()? Le void point i: deaw() { gotoxy (y, x) 7 puteh("."); , void point { assign_x(int 1 o1>2522! <1 ?Liry } void point :: assign_y(int c) yreo80280:e<171:07 , int point : { return x; 3 show_x0 14 C++ Programming int point 4 return y; 5 show_y() class line : if public point protected : int x1,yls public: line () ( wie, yi=1; i line(int r,int c, int rl, int cl) t assiga_x(ri7 assign_y (c); xl=rl>25225:rlei2iirl: } void draw(): void line :: draw!) { got oxy (show_y(), show_x()) iE (yl==show_y (0) patch(*."); ‘ for(int ( how_y() riceylsist) gotoxy (i, x1); putch (196) } ) return; } void main() i char reply; do ql elrser()+ int row, col, row1, coll; cout<<"\n Enter starting coordinator row, col cin>>row>>col; cout<<"\n Enter ending coordinator row,col:"7 cin>>rowl>>coll; if(coli Ldvaw(); gotoxy (3,24); cout<<" Wanna Contonue [y/n}:"; cin>>reply; ) while (reply== “ee y'll reply #include #include class insurance { protected : int no; char name(15]+ int years; float amt; public : void accept_data(); void show_data(); void insurance:: accept_data() cout<<"\n Enter, insurance no cin>>no, cout<<"\n Enter policy holders name cin>>name; cout<<"\n Enter policy amount eind>ant; cout<<"\n Enter no of years insured for :"; cin>>years; return; void insurance:: show_data() cout<<"\n insurance no :"<> rate_interest; caluculete_maturity(); retare; void payment :: display data() show_data(); n\n maturity value after period is "7 cout< #include class item { protected: int itemno; char itemname(15]; int aty, recordlevel; float rate; public void accept_data(); void show_data(}; ru voret Lecrinologies 5 7 CH Programming void item :: accept_data() i elrser(); cout<<"\n Enter item cin>>itemno; cout<<"\n Enter item name cin>>itemnane; cout<<"\n Enter item qty cin>>aty: cout<<"\n Enter item reorder level : cin>>recordlevel; cout<<"\n Enter item rate cimorate: return; , void item :: show data() ‘ > cout <<} Naresh i Technologies n item no :"<>salesno; cout<<"\n Enter sale qty cin>>saleqty; aty-qty-saleaty: Lf (qtys=zecordlevel) saleqty=0; saleamt=saleqty*rate; cout<<"\n sale amount return; level :"< Finclude class a ‘ protected : char name(15]; public: void accept () ‘ cout<<"\n enter your good name:"; , void show() cout<<"\n hai "<>i; ) void: show (.) Loe ari. show(); coutéc"\n number: "<e; ) void show() at:show(); cout<<"\n float is :"< #include class exp { protected : int nor char name(15]; public: void accept (}7 void show(); Me void emp { accept () cout<<"\n enter emp no"; ein>oni cout<<"\n enter emp good nam cin>>name; return; : void emp :: show() i cout<<"\n employee no ">sal: return; Temporary 81 (C#+ Programming Naresh i Technologies void permanent ‘ show() enp show (7 cout<<"\n salary: "<>wages return; , void temporary: :: show() ‘ emp: :show(); cout<<"\n wages per day: return; ) void main() { int choice; do clrser( cout<<"\n Employess maintainance system cout<<"\n Nain menu\n=======: cout<<"\n 1,Permanent \n2. temporary\n O.exit : cout<<"\n Enter u r choice cin>>choice; switch (choice) { case 1: permanent pi cout<<"\n Enter permanent Employee details + p.accept (17 cout<<"\n Displaying details p.show()7 break; case 2: temporary t; cout<<"\n Enter temporary employee details "; t.accept (7 cout<<"\n Displaying details 82 C++ Programming eeshow ()7 break: ) geteh () }while (choice>0sechoicec3) ; , Insurance Vehicle Personal #include finclude class Insurance i protected : int no; char name(15}; public: void accept (); void show(}; void Insurance :: accept () cout<<"\n enter Insurance no:"; cin>ono;, cout<<"\n enter name of the person:"; cin>>name; returns ) void Insurance +: t show() cout<<"\n Insurance no "<>veh_no; cout<<"\f Enter vehicle valu cin>>value; cout<<"\n Enter amount to be paid:"; cin>>amt; return; ) void vehicle ( show () Insurance :: show(); cout<<"\n vehicle no:"<>age: cout<<"\n Enter the amount to be insured for : cin>>amt: cout<<"\n Enter policy nam cin>>policy_nane; return; i void personal ‘ Insurance cout<<"\n Age cout<<"\n Amount to be insured for cout<<"\n policy name: "<>choice: switch (choice! case. 1 personal p; cout<<"\n Enter personal insurance details P-accept (); cout<<"\n Displaying details "; p-show () break; case 2+ vehicle v; cout<<"\n Enter Vehicle details "; v-accept (); cout<<"\n Displaying details v.show(} 7 break; 3 geteh(); Jwhile(choices2aachoice<3) ; /* calling from ¢ object : inherited from A cob} accept () 7 cob}. show() cout<<"\n calling from B object : inherited from A"; obj. accept ()7 bobj-show(); » Multilevel Inheritance Employee Rept Deputation = C+ Programming Finclude finclude class emp ( protected : int no, allot; vhar name{15}, pest (15+ public: void accept (); void show(); void emp :: accept () cout<<"\n enter emp no:"; cin>>noz cout<<"\n enter emp 3ood name cin>>name; cout<<"\n enter post applied:"; cin>>post + cout<<"\n is the employee is allotted for any joblyes=1/no-0) cin>>allot; return: fl void emp :: show(} t cout<<"\n employee no "<>dept; cout<<"\n Under whom (manager) :"7 cin>omgr; * cout<<"\n with how much salary : Naresh i Technologies 86 C++ Programming NNaresn 1 lechnologies cin>sa cout<<"\n is the employee is deputed to any other company [yes=1/no=0} : cimodepot; a , return; } - Ad recruit :rehow!) e emp: : show () 7 > | ig(allot) \ t > coutc<"\n To the*<édept<<" department 27 a cout<<"\n Under (manager) :"<>deput_no; cout<<"\n to which place deputed cin>>place; 4 return; WD i) ) void deputation ( show) recruit: :show(); if (dept) ; : cout<<"\n Deputation no"<«deput_noz cout<<"\n deputed to :"< Finclude class patient a t protected : int no,admit; char name(15], complaint (15]; public? x void accept (); void show (); : Me void patient :: accept () ra t eout<<"\n enter patient rors ein>>no a cout<<"\n enter patient good name:"; cin>>name; cout<<"\n enter complaints” cin>>complaint; cout<<"\n Is the patient admitted{yes=1/n , cin>>admit: ' return; of , je void patient :: show() eS cout<<"\n patient no: "<>inpatient_no; cout<<"\nnter Word Number allotted : cin>>word_no: cout<<"\n Enter Bed Number cin>>ped_no; cout<<"\n Enter Name of the Doctor in-charge cin>>doctor; cout<<"\n Is the Patient Operated [ Yes =1/No= 0] : cin>>operated; , return; : void admitted :: show() patient :: showiy; if (admit) ‘ cout<<"\n inpatient no :"<>0per_no; cout<<"\n Enter theater no "7 cout<<"\n Enter anesthesian doctor cin>>anest_docr ) return; ) void operation :: show() ( admitted :: Lf (operated! ‘ show ()7 cout<<"\n operation no :"< Hinclude Winclude class A { protected: char name[15] 7 (C+ Programming public: void accept (} t cout<<"\n Enter your good name :"; } void show() i cout <<"ai">e: } void show() { Bi tshow () 7 cout<<"\n float Number"<>sex; } void show() { cout<<"Gender is”<>name; cout<<"\n Enter Gender :”; cin>>sex; cout<<"n Enter any number :”; cout<<"\n Enter Float number :”; cin>>f; return; } 92 C++ Programming void C:: show() case ‘M’: cout<<"\n Hello Mr ,”< #include class employer i protected + char o: public void accept (15 void show(}; cout<<"'\n Hello Miss.”<>0rg_name; cout<<"Enter Manager cin>>manager; cout<<"\n Enter Deputation"; cins>dept; show() cout<<"\n organization name :"<>deput_no; cout<<"Enter to which place deputed cin>>place cout<<"\n Enter Organization name"; cin>>org_name; cout<<"\h To department cin>>employer :: dept; cout<<"\n under the manager"; cin>>manager; ) return; , void Deputation : show() i recruit ::. accept()s if (depet) ‘ cout<<"in Deputation number :"<édeput_no; cout<< “to which place depured :"< void main() ( elescr() + Deputation d; d.accept (); deshow(): Patient ited aes c~— Operated Bincludeciostream.t> 4include class doctor a protected int doc_no; char natie[15}, special (15), org{10]; public + void accept (); void show(); void doctor :: accept () cout<<"\n Enter Doctor no cin>>doc_no; cout<<"\f Enter Doctor name cin>>name? caut<<"\nEnter Speciatialization :"j cin>>special; cout<<"\n Enter organization"; cin>>org: return; : void doctor +: show() ‘ cout<<"\n Doctor no :*<>oper_no; Cout>theater_no; 1) coutec"\n Enter aneasthesian doctor"; cind>anest_doc cout<<"\n Enter main surgéon name accept () OX cin>>nane: cout<<"\n enter specialization"; \ cin>>specials cout<<"\n enter organization"; cin>>0rq; , return; m4 (\ Yoid operation 1: show adaitted +: show(); £2 L(operated) ( \ Cout< #include ¥include class shop ‘ protected : int aty; char shopname(15],name [15]; 3 float pric public + void accept () ‘ cout<<"\n Enter the shop name ": } cin>>shopname; return; ) void accept_one() ) : ) couts<"\n Enter the quantity purchased “7 eim>aey; cout<<"\n Enter total price “; ein>>price: retvrn; void show() ‘ cout<<"\n the quantity purchased "<>nanes CHP i a Programming class i cout<<"\n Enter the size of the item "; return; void show() ‘ cout<<"\n Size of the item "<>breed; cout<<"\nfnter the color of flower : cin>>color: zeturn; } void show() ‘ cout<<"\ri name of the flower bread :"< y . 1 pixchase : Public item, public flower protected int item_type; public : void accept (); void show(); accept () cout<<"\n Purchage entry form"; cout<<"1.stationary\n 2.Flowers\n 0.Exit"; cout<<"\n Enter type of item purchage : cin>>item_type: shop: :accept () 7 switch (item_type) ( case 1: item::accept(j; break; case 2: strcpy(name,"flower"); cout<<"\n enter name of item :"< When a pure virtual function is placed in the base class. it should be overridden in al the © derived classes from which the objects are created ,else the derived class gets converted to an abstract class : ee + Since an abstract class cannot be instantiated directly , one or more derived classes are normally defined as implementations of abstraction provided by abstract class 100 (CH Programming Naresh i Technologies A concrete derived class simply provides definitions for all of its inherited pure virtual functions % Ione of the inherited pure virtual funetion is not defined and if the class is instantiated the compiler returns an error message Late binding with object type cast : #include #include : class A { _ protected : ? int i; public: void accept () i cout<<"\x, Enter any Number : ) void show() t cout<<"a number"< class B : public A protected : float £; pyblic: . void accape () ) ‘ cout<<"\n Enter Any float"; cim>>t; void show!) 3 i cout<<"\n foat number "<>name; void show() ( coute<"\n Hai"é>choice; switch (choice) te case 1: obj -> accept (); obj -> shaw(); break; case 2: ((B*)obj) -> accept (); ((B*)0bj) => show(); break; case 3: ((C*/0bj) -> accept (); ((C*}0bj) => show() break; ’ geten() Jwhile (choice>0sachoices4); ) Late Binding with dynamic inifialization void main() ‘ A *obj; int choices do ‘ cout<<"\n call object of ; cout<<"\n 1.Class A \n 2.Class B \n 3.Class C \n O.Exit cout<<"\n Enter u R choice * switch (choice) 4 case 1 case 2: case 3: obj=new ) geteh(}; Jwht le (choice>0sachoice>4) ; i jew Az obj->accept (); obj->show()7 break; jew B; obj~>accept (); obj->show(); break; obj->accept (); obj->show(); break; 102 C+ Programming Naresh 1 Technologies Usage of virtual keyword #include #include class A ( protected : int 4; public: virtual void accept () { cout<<"\n Enter any number :"; eind>i; ) virtual void show() t cout<<"\a number :"<>choice: suitteh (choice) ( case 1: objmnew A; obj->accept ()7 case 2: obj=new B; obj->accept (); case 3: objenew C; obj->accept (); ) }uhile (choice>0&achoice<4) ; geteh(); } Geometric Example : #includeciostrean.h> Hinclude class point { protected int x,y? public: void set_xy(int, int); void draw(); void point: :set_xy(int c=0, int ‘ xec; yer ’ void point: :draw() ( gotoxy tx, ¥)2 cout<<"point"; obj->show(); break; obj->show(); break; obj->show(); break; 104 C+ Programming Naresh i Technologic3 class circle : public point fi protected : ‘ int radius; public: woid draw() ‘ cout<<"\n Circle"; ; ' be class ellipse :public circle i protected int y radius; public? void draw() ‘ cout<<"\n Ellipse"; z 7 : ) void main() > t 3 char object_type_array(20], reply, object_types point *£[20]; int counter=0; oy do - C reply=" cirser(}; cout<<"\n C/e.Circle \n B/e Ellipse \n X/x Exit "7 cout<<"\n Enter u R choice " a ‘cin>>object_"ypes switch (object_type) 3 ‘ case tc case 'Ct: f[countes]=new circle; break; 7 case te : case case ) object_type_array[countert#]~object_types Iwhile(reply=="y"| | reply=="¥"); cout<<"\n Displaying the figures . for(int ctr-07ctrdraw(); break; case case ! geten(); } ((ellipse*) £{etr])->draw(); breal H+ i 15 C+ Programming Naresh i Technologies cx Using Virtual Keyword : #include Hinclude class point { protected int x,ys public: : void set_xy(int, int)? virtual Void draw(); a M . void point:set_xy(int c,int r) . t ao i oyees a } void point::draw() ce ( cout<<"point"; o , : class circle : public point Q { protected : int radius; public: void draw() ( cout<<"\n Circle"; ? . he ie class ellipse :public circle ( 7 protected : ‘ int y radius; public: ie void draw() { a coutcer\n Ellipse ig void main() char reply="y', object_type; point *£[20]; int counter=0; do clrser() cout<<"\n C/e.Circle \n E/e Ellipse \n X/x Exit "; oP ~~ C++ Programming iaresn | |ecnnologies cout<<"\n Enter u R choice *. cin>>object_type; switch (object_type) ( case ‘Ct: £(counter]=new circle; countert+; break: case 'E': f[counter]=new ellipse; countert+; break; case 'X': reply='n'; } Jwhiietreply=='y"| | reply=="¥"); cout<<"\n Displaying the figures ~ for(int etr=0;ctrdraw() 7 geteh (); Constructors and Destructors in Late Binding A include #include 1 class A . t + protected Cc ine i; public ‘ A () { cout << “\n A constructor called. ~A( ) { cout << "\n A destructor called. * 7} class B : public A protected: float f7 public: B( ) ( cout << "\n B constructor called." 7} ~B() { cout << "\n B destructor called." 7} class C : public B protected: : char name [15]; public : () ft cont <« "\a © constructor called. “C( ) { cout << "\n C destructor cali - C++ Programming void main( ) 4 A*ob}; int choice; do ( elrser( )7 cout<<. "\n call object of "+ Naresh i Technologies cout << "\n }.class A \n 2.class B \n 3.class C \n O.exit."; cout << "\n enter choice (0-31 : "; cin >> choices ~~ switch (choice) 1 case 1: bj. = new A; delete obj ; breaks case 2: obj = new B ; delete obj ; break; case 3: obj ~ new C ; delete obj ; breaks ) getch( ); Jwhile ( choice > 0 && choice < 4); class A { protected : inti; public : AQ) { cout #include class A protected + int x7 public + void show( ); B+ public A protected : float £; public : void show( } G cout << "\n fr" >name; } void show! | ( cout << "\n hai" << namec< "1" ; d > ye ) class D: public ¢ i } publi . void accept ( } ( Cz: accept( ); cout << "\n enter any number :" ; cin>dx; cout << "\n enter any float :" ; cin>>f; void show( } i Ct: showy; Bi: showl )7 : cout << "\n number is :" cex 7 ) 109 C+ Programming void maiat ) 1 0 obj; obj.accept( J+ obj.show( ); Naresh i Technologies EMP L Permanent ‘Temporary finclude #inelude class emp 1 protected int nes char name[15}; public : virtual void accept ()=07 virtual void show()~07 hi class peranent : public emp fi protected : float sal : public + void accept () void show() 7 ir void permanent :: accept () t coutc<"\n Enter. Enployee No : cindono; cource™(nknter Employee Name : * cins>nane? : eout<<\n Enter Salary : "7 cin>>sal 7 return 7 + void permanent :: show() t coutce"\n Employee No :"<>nos cout<<"\n Enter Temporary Employee Name : cin>>name ; cout<<"\n Enter Daily Wages cin>>wage ; return ; ) void temporary :: show() 5 i > cout<<*\n Temporary Employee No + "<>choiée ; switen (choice) ) i case 1: permanent p; cout<<"\rEnter Permanent Employee Details p.accept {) cout<<"\nDisplaying Details p.show() break; case 2: temporary ty cout 0 && choice <3) ; ui (CH Programming Naresh i Technologies Ambiguities Galore to Virtual Base Class : #include #include class A { protected : int x; 2 public : 5 void accept () : ( cout<<"\n Enter x 2"; ) void show() { coutse"\n x ) class 2: public A ‘ protected : float £; : public : void accept () i cout<<"\n Enter £ :" 7 cindst ; , void show) 1 cout<<"\n £ "ect 5 ) iy C+ Programmin; 112 iat Naresh i Technologies class © : public A ‘ protected : char name(5]7 public + void accept () ‘ cout<<"\n Enter Your Good Name :” cin>>name ; ¥ void show() { cout<<"\n Hai Hincludecconio. m> class A 4 protected : int x; public : void accept (} 1 coutce"\a Enter x 113 (C+ Programming class B ' e void show() ‘ couts<"\n x 2 " class’D : public C, public B t Me public + void accept () t accept(); Br: accept () + ! void show() Br rshow(]s 7+ Allowed accept () 77 Allowed 7 Naresh i Technologies 14 C+ Programming ryuresn 1 recrinologies void main() ( D obj: 0bj accept () 7 Ob} .show() ; ) FRIEND FUNCTIONS : ~ * The Private Members cannot be accessed from outside the class ie. anon member ‘function cannot have an access to the private data of a class. “ Inreal world programming there could be a situation where we would like two classes to share a particular function. ‘© In C++, the common function can be made friendly with both classes, which allows the function to have access to the private data of these classes. These types of functions need not be members of any of these-classes. “ To make an outside function “ friendly * to a class. The Syntax is as follows : class < Class Name > ( , i tember ; i public members; 3 friend void < function name > ( arguments ) ; b ‘The function declaration should be preceded by the keyword friend. ‘The function definition does not use either the keyword friend of the scope operator :: A function can be declared as a friend in any number of classes. A friend function, though not a member function has full access rights to the private members of the class. Friend Function Characteristics : Itis not in the scope of the class to which it has been declared as friend. Since it is not in the scope of the class, it eannot be called.sing the.object of that class. 4 Incan be invoked like a normal function without the help of any object. + Itcannot access the member naines directly and has to use an object name and dot membership operator with each member name. * Itcan be declared either in the pubic or private part of the class. + Ithas objects as arguments, + A friend function can be called by reference. % In this, a pointer to the address of the object is passed and the called function directly works on the actual object used in the call. * The above method can be used to after the values of the private members of a class. ) = C++ Programming finclude class A i private + int x7 public + void accept () i cout<<"\n Enter x + cin>>x; , friend int. add_objects(A,.m)+ Ww int add_objects (A al, A a2 ) ‘ return ( al-x + a2. )7 1 void main() t Ral, a2z al.accept () 7 a2.accept (17 cout<<" \n Sum of Both Values :"< class B; // Forward Declaration class A ‘ private : int x; public + void accept () 4 cout<<"\n Enter x + cine x: 1 void show!) t coutse™\n x M private : int yz public + friend int sum(A,B); void accept (} ‘ . . cout<<"\n Enter Yi"; + cin>y; . } y void show() ° fl cout<<"\n y Mee ye h int sum( A al, Bb2 ) ~ i return( al.x + b2.y J+ } void main() : i . Ral; Bb el.accept () . b2.accept () 7 cout<<"\n gum is "< #include class emp a { protected = 5) int no; : char name {15}; . public: void accept( } + void show( } : Me 7 woid emp :: accept ( ) ‘ cout << “\n enter employee no :" 7 cin>>no: cout << "\n eater employee: name i" ; cin>>name; return; et ‘ing 1 CH Programming Naresh i Technologies y void emp :: show() { cout << "\n enter employee no :" < float sa public : : - vold accept ( = i y void showt Exiend void incone_tax (peranent, temporary, int) Me d Hi void permanent :: accept (.) { emp :: accept ( ); cout << "\n enter salary,:" 7 cin>>sal; return; ) Leu show( ) void permanent 4 t emp i: show( ): ) cout << "\n salary :" <>wage; return; ‘ ) A void temporary :: show( ) i { emp i: show( }7 “ cout << "\n wages per day :" < cout << "\n 1.permanent \n 2.temporary \n 3.both \n Q.exit™ 7 cin>>choice; 3 switch (choice) : i : 3 cout << “\n enter permanent employee details :* p-accept ()7 cout << "\n displaying the details : p.show()? 7 if (choice!=3) a break ; _ case 2: cout << "\n enter temporary employee details :" ; . t accept (); 3 cout << "\n displaying the details :" + teshow(): break; ? income_tax (p, t, choice); getch(~): } } while ( choice >0 & choice<4); #include #include #includecstring.n> class teacher ; class stud_teachs //forward declaration class student Hi protected + int nos +) + char name [15) ; a int class_study +t Pi aD C++ Programming v Naresh i Technolagies Float fees ; public student () ( } student (int x) ( } void accept ( )7 void show ( )7 friend void fees_pf (student &, teacher &, stud_teachs, inte ); i void student tt accept ( ) cout <<:"\n enter the student no cin>>no; cout<< "\n enter the student name : cout<< "\n enter the class cin>>class_study; return + } void student :: show( ) i cout << "\n student no :" <>no + cout << "\n enter the name of the teacher cin>oname ; cout< "\n enter the subject cin>>which_subject + cout << "\n enter the salary return 7 p cins>sal ; i void teacher +1 show( ) { cout << "\n employee no :" >student 2: no; cout<<"\n enter employee no cin>>teacher ino ; cout<<*\n enter his / her name + cin>>student :: name ; stropy (teacher :: name, student cout<<"\n enter class of study cin>>student :: class_study ; cout<<"\n enter subject teaching cin>>which subject ¢ : accept ( ) name) + covt<<"\n enter the salary :" ; cin>>sal ; retura ; a void stud_teach :: show( } { cout << "\n student no :" s.fees + break 7 case 2: cout << "\n enter provident fund tpg = t.sal * 0.1; cout <>choice student $7 teacher t ; stud_teach st ; switah (choice) S.accept ( fees_pf(s, t, st, choice) cout << "\n displaying the details cout << "\n student data entry form s-show() 7 break ; case 2: cout<< "\n teachers data entry form t.aecept ( 7 fees pf(s, t, st, choice) cout << "\n displaying the details." ; Eeshow( ) 7 break case 3: cout << "\n student _teachr data entry form." ; staccept()). 7.9‘ sae) BROS pL (3 pak ‘SE. Show() 7 break + } getch (); } while (choice >0 && choice<4); Class : Hinclude Hinclude class public a int x7 friend class b; void accept ( } i cout << "\n enter any number f ochn ox 5 me ce Mn dighigyina the detail 373 t 122 C++ Programming yee class b t int yi public = void accept ( } ( cout << "\n enter any numbaer :"; cinp>y ;) void show( a al) cout << "\n value of number of class a :" % Unary operators, overloaded by means of a member function, take.no explicit arguments -ewand: return no-explicit-values.: But those overloaded by means of a-friend function takes one reference argument. ‘ Binary operators, overloaded through a member function take one explicit argument and those which are overloaded through a friend funiction take two explicit argument. + When using binary operators, overloaded through a member function, the left-hand operand must be a object of relevant class. * Binary arithmetic operators such as + ,-, * and / must explicitly return a value. They ‘must not attempt to change their own arguments. include #include Hincludecstring-b> class word c private : char ‘str? int lens public + wordt) ‘ len=0; stx=07 ) word( char * ) int operator == (word 6); word operator + ( word & ); char * show( ) t i return str; > = C++ Programming sw eon Lecnnoiogies sword ) ( delete ste: } ie word :: word ( char ts ) ‘ ten = strlenis): strsnew char|len+)}7 strepy(str,s); a strepy (str, 8); i s int word :: operator == ( word és) { peturn { steemp(atesa.atei== 0)21:07 | ) word word 1: operator+(word &s) _ . ? temp.ien = len + s.len; tcemp.str = new char[temp.len + 1]7 strepy (temp. str, str); : streat (temp. str,s.str); return temp; ; ) void main( ) i elrser(); 5 char *name; cout<<"\n Enter First Name cin>>aame: word a (name) ; couc<<"\nEnter Last Name cind>name? word b{name} ; -, if(as=b) cout<<"\n Hai "< #inelude class quardatic i private : int a, by cf public : quardatic( ) { a=0; b=0; en; , quardatic( int x ) quardatic( int x, int y ) ( bey; cn0; : quardatic( int x, int y, int z) { bay? , quardatic operator + (quardatic p); quardatic operator ~ (quacdatic p); void operator = ( ); y+ Unary minus void show equation () i cout<<"\ntccacc"xn2t (Mecbesmx )+("<>a; cout<<"\n Enter Coefficients of X*1 cine>bs cout<<"\n Enter Coefficients cin>>e quardatic Q ( a, by c) » Ar Q.show_equation( )7 cout<<"\n Applying the Minus :"; 07 77 Unary Minus; Q. show equation () cout<<"\n Enter only the X*2 Coefficient to the equation cin>>ay cout<<*\n Addiag the entered value to the equation: "; AeQtaz : cout<<"\n The Resultant Equation is :"> A, show_equation() 7 cout<<*\n Enter Coefficients values for second equation: cout<<"\n enter Coefficients of x°2:"; cin>>a; cout<<"\n enter Coefficients of x*1:", cin>>by cout<<"\n enter Coefficients of X™0:"> cine: quardatic pla,b,c)? cout<<"\n The Bguation is :"7 p.show_equation( ); cout << "|p subtracting the two quadratic equations cout << "\n the resultant quadratic equation is :" 7 Avp-0 7 AA. show_equation{ ); d C++ Programmi 127 a ; Naresh i Technologies i Milustration of Data // ) #includesiostream.h> #include : , class date ( : private + int dd mm,” yy 7 ) public + date ( ) t ) dda ; ) : date (tnt d, tnt m, int y) ) int operator == ( date 6) void show date () 7 2 : date :: date (int d, int m, int y) { yy= ysl980 ? 1980 zy; J m= m>12712 ; mcl2Lim 7 : 431231 3 delelid + Af (yy == a.yy) return 1; a xeturn 0; return 0; : ) ¥ void date :: show_date( } ( a cout << "\n the date :" add>omm>>yy 7 date didd, mm, yy) d.show_date( ) 7 cout << "\n illustration of comparison of two dates cout << "\n enter day, month year :"; cin>sdd>>mm>>yy : CH Programmi 128 . Naresh i Technologies date dl (dd, mm, yy); dl-show_date( ); if (d == di) cout << "\n dates are equal :" else cout << "\n not equal" ; Ilustration of Friend Operator #include #include class quardatic private : int a, b,c? public + quardatic ( ) ( aed 5 beO ; on0 F , quardatic (int x] { ) gquardatie (int x, int y? (int x, int y ,int 2) 2 bey? cxzz void operator ~( int operator -=(quardatic p) ‘ if ( ¢ a== pa) && ( ( BES pb) 8& ( o™ pic) )) return 1; else return 0; , feiend quardatic +(quardatic r, quardatic s); oH - CH Programming Naresi i Technologies quardatic operator + (quardatic r, quardatic s) quardatic temp + temp.a = r.ats.a ' temp.b = r.bts.b ; temp.g = r.cts.c 7 return temp ; } void maint } c { int.ay-b, ci /. scout <<""\n iijustration of commutative property with friend” ; cout << "\n-enter coefficients for equation 1: cout << "\n enter coefficients of x*2 :" ; cin>a ; cout << "\n enter coefficients of ¥*1 :" ; cin>>b ; cout << "\n enter coefficients of ¥"0 :" 7 cin>>c ; quardatic g(a, b,c)? q-show_equation( ) 7 quardatic A=gt5 ; A.show_equation( ) ; : quardatic B=1+q + B.show_equation() i Af (an=b) 2 cout << "\n equations are equal :" ; else cout << "\n not equal" ; a ; lustration of Overloading of << and >> Oper: Hincludeciostream.h> #include class date : { private : int dd, mm, yy 7 . public = date( ) : { : da=1 ; nme ; . yyel i: 7 date (int, int, int); int operator ==(date &) 7 friend ostream & operator <<(ostream &, date &) friend istream & operator >> (istream & date &) + ostream operator << [ostream &s, date ga) { acc "\n" <>a.dd>>a.mm>>a.yy 7 return 5; date (int d, int m, int y) yy> y<1980? 1980 zy ; mm=m>12?12 : mc1271: dd=d>31?31 :d<1?1:d 7 int date :: operator ==(date 4a) ( if (do-sa.ad) if (nm=na.mn) Af (yma. yy) return 1; else 5 return 0; return 0; 4 7 . vold main{ ) ( int dd, mm, yy ; cout << "\n enter the day, month, year i"; date d: cinssd ; wyOh oe mete OE , soutcd j 2 cout << "\n illustration of the comparison of two dates 3"; cout << "\n enter day, month, year :" ; y gate dl: . ein >>dl ; . cout < The dis qualification of dynamic binding are the executions being shower and memory dump, d % Static binding does not needs runtime search for the code, which makes code faster. 4 FLEXIBILITY: 4 4 As applications become larger, they become more complicated and need for flexibility increases. / ‘Static binding makes s/w upgrade more tedious, since change in any past of the code rippies the entire project. > In dynamic binding, the function calls are resolved at runtime, giving the user the flexibility to alter the calls without modifying the code. “> For a programmer efficiency and performance-are primary concerns; but-to the users flexibility or maintainability are primary concerus. ~ Polymorphis: Compile time \. polymorphism polymorphism Function Overloading Operator Overloading 132 C¥ Programming iuresn | Fecnnoiogies Overlozding Overloaded Operator : #include #inelude class fps_distance { private = int feet ; 5 float inch public + fps_distance (int, float) ; fps distance operator + (fps distance &) + fps_distance operator + (int inches) ; void display( ) ; i fps_distance =: fi fps_distance (int f=0, float 4: feet = £7 inch =iz ) fps_distance tps_distance :: operator + (tps_distance étp2) { int fafeet + fp2.feet ; a float ie inch + fpecinch 3 if (bei2.0) return fps_distance (f, i) i fps_distance fps_distance :: operator + (int inches) ( int f=feet + (inches / 12) ; (inches 812) ; return fps_distance (f, 1) ; } void fps_distance { display( } cout << "\n distance =" <>£ ; gout << "\n Enter inches ein>> in; fps_distance fpl(f; in) 7 > fpl.display( ) 7 cout << "\n Enter another measurement :" ; cout << "\n Enter feet :" 7 eine ; cout << "\n Enter inch 2"; ein>> in; fps_distance fp2(f, in); fps_distance fp3 7 #p2-display( ) ; cout << "\n adding the two measurements : £p3 = fpltfp2 + cout << "\n the result fp3.display( ) + cout << "\n Enter other measurement only in inches :" ; cin >>in ; fe3 = fpl + in; cout << "\n the result is : fp3.displayi ) ; Overloading new and delete operators: # include # include # include # include int confirm = 0; const int MAX=3 ; const int FREE =0 7 const int OCCUPIED =1 ; void memory alert ( ) ( cout << "\n sorry! memory is filled” ; return ; ) . class student i ‘ i private : int no 7 char name (15) int class_study ; CH Pi 4 CH Programming public = student ( ) { A no = 0 7 name (0]="\0* class_study=1 ; ~ : void * operator new(size_t) + void operator delete (void *q) ; void accept_data() ; void show data} ; a ~student (-) ; typedef struct sharednenory ‘ student stu_obj ; int status Mv sharedmesory *mem=NULL ; void *etudent :: operator new(size_t size) A i ey int iz a if (confirm==0) ( mem (sharedmemory*) malloc (size *MAX) ; if (me confirm=1 ; 2 nen{0}.status =0CCUPIED ; 5 return énem[0] .stu_obj > } else 5 { L for (i=0; i>class_study; ) void student ‘ show_data( } cout << "\n student no :" << no; cout << "\n student name :" accept_data( } ; ) cout << “\n displaying the list :"; for (is0; icHAX; i++) s[i] ~>show_data( 17 cout << "\n \n enter the record no to be deleted delete s(4] ; F cout << "\n \n displaying the delete record details :" 7 s[i] ~>show_data( }; cout <¢ "\n \n now reassigning a new record in place of deleted record” boesni s cout << "\n \n trying to allot a enter record above the allocated memory" kenew student ; = C++ Programming, Naresh i Technologies . CONSOLE MANAGEMENT I/O OPERATINS : ‘The C++ 1/0 stream can interface itself with variety of devices including terminals, disks and tape drives. + The interface provided by the C++ is known as stream. + A stream is a sequence of byies it acts either as a source from which the input data can be obtained or as a destination to which the output data can be sent. % The source stream that provides data to the program is called the input stream. “The destination stream that receives output from the program is called the output stream eb cthepro gram extracts the bytes from an input stream and inserts bytes into an output stream + A stream acts as an interface between the program and the input/output device, STREAM CLASSES IN C++ * C+ /O system consists of a hierarchy of classes that define.various stream. ‘The classes are called as stream class. +> The classes are declared in the iostream.h header file. >| ostream | | Istream_with assign { Tostream_with assign Ostream_with assign Stream Classes for Console 0. Operstions “4+ iosis the base class for istreamvand-ostream; which outs as base classes for jostreara, % Class jos is declared as the virtual base class, such tt only one copy of its members are inherited by the iostream. Class ios provided the basic support for formatted and unformatted /O operation. Class ostream through inheritance provides the facilities for formatted output. The class iostream provides facilities for handling both input and output streams. The classes istream_withassign, ostream_withasign, and iostream_withassign add assignment operations to those classes, * * + C+ Program: 137 ee Naresh i Technologies ios : General input / out put stream class) “Contains basic facilities that are used by all other input and output classes. ‘> Itcontains a pointer to a buffer object + Declares constants and functions that are necessary for handling formatted input and output operators. Istream : input stream : Inherits the properties of ios. + Declares input functions such as get( ), getline( ), & read( ) Contains overloaded extraction operators>> Ostream ; output stream : * Inherits the properties of ios. Declares output functions such as put () and write) Contains overloaded insertion operator <<. Jostream : input / output stream, + Inherits the properties of iestream isd ostream through multiple inheritance and these contains all the input and output functions. Stream buf: - * ° Provides an interface to plivsical devices throug! buffer It acts as a base for file buf class used in files. UNFORMATTED I/O OPERATIONS OVERLOADED >> and << OPERATORS Cin and cout are tsed for the input and output of data of various types. >> and << operators are overloaded to recognize all-the basic types of C++ the >> operator will cause the compiler to ‘pause the execution for some time and look for input data from the keyboard. At mun time the values should be entered are separated through spaces, tabs or new lines. ‘The >> operator reads the data character by character and is assigned to the indicated address. 138 C++ Programming Naresh i Technoiogies Past( fun ‘> Itis defined in ostream class. % It is used to handle single character output operations. % The general syntax of declaration cout. put (‘value’) ; cout. Put (variable) ; var cout. put (ASCI) ; * The process gets terminated as soon as a new line character is encountered. ible should contain a character data get( fumetion = % Its defined in istream class. * Itis used to handle single character input operations. “The general syntax : cin.get( ) //int get(void) ; cin.get(variable) ; {stream & get (char *, int len, char = ‘\n’) ; > extracts characters into the given char * until one of the following occurs. 1. the delimiter (third parameter) is encountered 2. end-of-file is encountered. 3. (len-1) bytes are read. >a terminating null is always placed in the output string, + the delimiter is not extracted from the input streams. — fails only when no character are extracted, write() % itis line oriented output function. + lt can display a line of text more efficiently > The general syntax of declaration: cout. Write (line, size) ; ‘the first argument “line” represents the string to be displayed: =~ * the second argument ‘size’ indicates the number.of characters to display. It does not terminate when null is encountered. 4 Itsize is greater than line length, then displays beyond the bounds of the line. If can be used to concatenate two strings cout. Write (stringl, size). write (string2, size) ; * getline() function : % Itreads a whole line of text that ends with a new line character. ‘© The general syntax of declaration is cin.getline(line, size) ; _ C+ Programming Narésh i Technologies + The reading is terminated as soon as a new line character is encountered or size-1. character are read, The new line character is read but not saved instead is replaced by a null character. — istream & getline (char *, int , chr ="\n") ; * extracts upto the delimiter Formatted CONSOLE 1/0 OPERATIONS : y 2» 3) 4 + manipulators. user defined output functions width() > takes an integer argument which specifies the /O width —> for cin, only the specified number of characters are read. — for cout, the output is displayed right justified in.a field ofa-specified width.» — of the length of the field is greater than the current width, the entire value is displayed for cout Precision () — takes an integer argument which specifies the number of digits after the decimal point. — involved when a float or double is displayed. —> returns the current number of decimal places. () — iakes a character argument which specifies the character to be used for padding extra spaces when calling width( ) — is the default fill character > involved only if the value set using width is grater than the-length of the inserted value. - skipws : — of set, any leading white spaces are ignored on the extraction — set by default. — if not set white spaces are ignored. left and right : only one of these may be set at any time. L — if lefts set, inserted data is left justified. — if right is set, inserted data is right justified, a (C+ Programming Naresh i Technologies 6) showpoint : > forces trailing zeros and decimal points in float and double insertions = > not set by default. 7) ling self (long f, long uf=0) — sets the format flags in f — if the second argument uf, is specified the format flags in uf will be unset by default its value is zero. — retums the previous flag value. 8) long unself (long f) : - > clears the siogs that are set in £ > return the previous flag value, Ji 9), Showpas : — forces a plus sign before a positive number 2 > not set by default. ; 10) show base : > uses base indicators on output 11) upperease : > uses uppercase letters for hexadecimal output 12) skipws : 5 ~> skips white space on input 13)unit but: > flushes all streams after insertion 14)stdio — flushes stdout and stderr after insertion 5 Cr+ Programmin; 14h eee Naresh i Technologies Note 1) the flags set by self () remain effective until they are reset or unset 2) a format flat can be reset any number of times. 3) Wecan apply more than one format control jointly on an output value 4) The self () sets the specified flags and leaves others unchanged, MANAGING OUTPUT THROUGH MANIPULATORS : ¢ The manipulators funictions are declared in iomanip.h header file The functions are similar to ios member function and flags *& Some manipulators are flexible, when compared with ios, two or more manipulators can be used as a chain in one statement making columnar display earlier. set w (int w) : — sets the field width to w : set prevision (int d) : ~ sets *he floating point prevision to d set fill (int ©) = — sets the fil characters to ¢ set ios flags (long f) : > sets the format flag £ reset ios flags (long f) : > clear the flag specified by f endl : — insects new line and flush streams User Named Manipulators: ¢ Manipulators can be designed for customized purposes wo (C++ Programming Naresh i Technologies Syntax: ostream & manipulator (ostream & output) { (code), return output 5 } #includeciostrean-h> #include void main() ( char *stc? cout<<"\n Illusttation of Input with >>"; cout<<"\n Enter your address : cineostrs cout<<"\n The Addzess :“ #includecconio.h> Hincludecstring.h> void maint) { char ame(25],desig(25}, address [150]; cleser(); cout<<"\n T1ilustration of cin.getline():"7 cout<<"\n Enter Your Full Name : cin.getline (name, 25, "\n"}; cout<<"\n Enter Your Desi cin. getline (desig, 25, '\n") cout<<"\n Enter Your Address :"; cin.getline (address, 150, "\n"); cout<<"\n Iliustration of output with ‘<<" cout<<"\n The Details are :"7 cout<<"\n Name :"< Hinclude define N 2 class shop i private : int no; ‘ char name(15] float price; int ty: public : void accept () void show(); h void shop tl accept () : elrser(); 4 cout<<"\n Enter Ttem No cin>>no; char c= cin.get ()/ cont<<"\n Enter Item Name :"; cin.get (name, 15) ; cout<<"\n Enter Quantity Purchased : cin>>qty: - cout<<"\n Enter Price of Zach Item cin>>price; return ; 5 : void shop :: show() 4 cout . sett [ios::showpoint cout. set f (ios: :showpos) ; cout. £112 ("*"); : cout .width (8) cout . set f (ios: cout < #inelude Sincludeciomanip.h> void main() i float ¢, £1, £2, £; clrser(); cout<<"\n Enter the starting Temparature in Farenheit :"; cin>>El; cout<<"\n Ebter the Ending Tempparature in Faranheit cin>>£2; elrser i); cout<<"\n Faranheit \t Celesius \n === for(f=£1; £¢£2; f=£+0.5) c=( 5.0 / 9.0) * ( £3295 cout< #include define N 2 class shop { private + int no; char name[15]; float price; int aty; public + void accept (); void show()7 Me ostream & number ( ostream soutput) ‘ output .setf (ios: :showpoint) ; output -£i11('*"); output width (8); output -precision(2); output -setr(ios::right, ios::adjustfield); return output; ) ostream & message ( ostream & output) t outpae. £4110 4); output. width/15) ; output. setf (ios return output; left, ios: sadjust field); ostream & monetory ( ostream & output) ‘ output. fi1l(" "); output<<"Re. "7 output precision (2); output setf(ios::right, ios: :adjustfield) ; return output: d void Head () ( elrser(); Naresh i Technologies cout<<"\n Item No \t Item Name \t Price \t Quantity \t Value \n"; return ; 146 C+ Programming void shop :: accept () t elyser(); cout<<"\n Enter Item No :"7 ein>>no; chat cmcin.get (7 cout<<"\n Enter Item Name : cin. get (name, 15) ; cout<<"\n Enter Quantity purchased cim>gty; Fi cout<<"\n Enter Price of Each Item : cin>>price; return; void shop ‘ cout< The classes defining file handling methods are ‘ifstream’ , ‘ofstream’ and ‘fstream” +> The above ciasses are derived from ‘fsiream base’, which is declared in fstream.h. 1: file buf: « itsets the file buffers to read and write, * contains open prot constant used in open( ) of file stream classs. * contains open( ) and close() as members. 2:: fstream base : * contains operations common to the file streams * serves as a base for fstream, if stream and of stream classes. + contains open ) and close ( ) functions. 3: ifstream : + provides input operations. + contains open () with defanlt input mode. © inherits. the functions get(, getline () , tead Q, seekg-Q and tellg() functions from ‘istream’ 4: ofstreai «provides output operations. . # contains open( ) with default output mode. « inherits put( ), seekp( ), tellp( ) and write() functions from ostream. 5: fstream : « provides support for simulations input and output operations. + contains open ) with default input mode. «inherits all the functions form istream and ostream classes through ‘iostream’. FILE OPENING AND CLOSING ACTIVITIES: “ To opena file, first create a file stream and then link it to the filename. - C+ Programming Nai esh i Technologies + The file stream is defined using the classes ifstream, of stream and fstream through fstream.h 4 The methods applied in opening a file are —> using construetor function of a class, used when stream contains only one file. —» Using members function open( ) of the class, used when multiple files have to be managed using single stream. = eae fstream [ ofstream ——___»| stream base APPLYING CONSTRUCTORS ON OPENING FILES : * A file name is used to initialize the file stream object applying following steps: + Create a file stream object applying appropriate class. > Initialize the file object with the desired @lename. Syntax : ofsiream (“filename”) ; ifstream < file object name> ( “filename” ) ; 4 When the stream object expires the connections with a file is automatically closed. USING OPEN FUNCTION : 4 Open function is used to open multiple files that use the same stream object, 24 i He i WO C++ Programming Naresh i Technolog Syntay ; . open (“filename”) ; END-OF-FILE : ‘© The end-of-file condition is necessary to prevent any further attempt to read data from the file. “> éof () isa member function of ios class, which retums a non-zero value if the end-of- file (EOFO condition is encountered ‘the member function is declared over a ifstream object. OPEN () FILE MODES : «the file stream object can take two functional argument one-filename:andithe second if is file mode. Syntax: . open ( “filename”ra fuke_mode) ; ‘> the second argument gets applied with default file values, under the ebsence of actual values. ‘> The default values are 1) ios :: in > for ifstream function which opens file for reat only purpose. 2) ios: out ~> for ofstream functions which opens file for write only purpose. ios : : app — used to append to end-of-file. app —> moves to end -of-file on opening. ios :: binary —» used for binary file representation. ios : :no create—> opening of a file fails of it does not exists ios : :no replace-> opening of a file fails ifthe file already exists trunc —rdelete contents of the file if it exists. io io Soe eee io Points TO Ponder : 1) a file opend in ios :: out also opens it in the-ios =: trune mode by default 2) both ios :: app and ios :: ate both uavigate us to the end of file when it is opened app allows data to be added only at the end of the file. ate permits data to be added or modified any where in the file. 3) ios: : app parameter can be used only with files capable of output. 4) If stream implies input and ofstram implies output, hence it is not necessary to provide mode parameters. 5) fstream class does not provide a mode by default hence the mode should be provided using an object of fstream class. 6) The mode can combine two or more parameters using the bit wise OK ‘!” operator. ios ios = C++ Programming Naresh i Technologies open ( “filename”, model; mode2 ; moden) ; f include W include void main( } ofstream out ("first-drg") + , int x7 cout << "\n enter any number cout << "\i for (int ( out , #include finclude void main ( ) clrscr( ofstream outfile ( "CHARL.txt") 7 char c, ch(15] ; cout << "\n enter any character ; to terminate pres int i=0 + cout << "\n writing the data to the file character by character while ( (c= cin.get( ))!= 'x") i entit4] = 07 outfile.put (el + } outfile.pue ("40") + outfile.close( ); cout << "\n reading the data from the file ch: ifstream infile ("CHARL.txt") 7 char * str; , iO; 3 cout<< "\n the data read form the file is: c:"; cter by character"; H+ Pr i tl C++ Programming, Naresh i Technologies while (infile) ‘ infile.get(c) ; cout .put (c) 7 str [i] = 0; } infile. closet ) + cout<< "\n the data read from the file : str : < #include #include void main (int argc, char * argv[]) t if (arge<3 6& argo>3) ‘ cout<< "\n invalid arguments : type file copy return ; 3 ofscream dest (arav[21, ios ifstream source (argv[1], ics cout << "\n copying the data from our) in) << azgy[1] << "to" << aravi2y ce" char ¢7 source.get (c) ; while (source) ‘ dest-put (ce) source.get (c) cout << "\n file is copied . thaukyer for using the file copy utility 7"; dest .close( ) + source.close{ ) + #include # include # include class vehicle ‘ private int no 7 char model (8: float price ; +P 3 C++ Programming Naresh 1 Technologies public + void accept ) ; void show( ) void write vo file}: void read_from_file( ) ; - void append to_file( } ; woid vehicle #: accept( ) ‘ cout << "\n enter serial no :" 7 cin>>nos cout << "\n model name :" ; cin>>model; cout << "\n enter curren price:" ; cin>> price ; return ; , void vehicle :: show( } ‘ cout << "\n serial no :" ofstream outfile ("vehicle.txt") = char reply ; int i=; do i 7 cout << “\n enter" << itt << "vehicle details :" ; oe accept ( ); outfile << noce " * cour << "Nn any more (y/n] i" 7 cin>>reply + Jwhile(reply=="y" || replys="¥"); 5 outfile.close( 1; ° return 7 ) vois vehicle t read_from file( } ifstream infile ("vehicle.txt") + ine i=1 ; infile >>no infile >>model ; infile >>price while (infile) { coutcs "\n record no:" <sno ; infile>smodel + é wi ‘ 153 C++ Programming ‘Naresh ! Technologies infile>>price ; getch( }7 } infile.close( 1; } - void vehicle :: append_te_file( ) t ostream PP) i char reply 7 ° do { > 3 accept ( }; : outfileccno<<' "<>reply + d ) while (reply- IL reply== ty") + outfile.close(}; : a return ; , 3 void maint } i ( 3 J elrser (07 iat choice ; vehicle v7 3 , do £ e cout << "\n main menu" ; cout << "\n I.new file \n 2.read \n 3.append date \0-exit"; cout << "\n enter choice [0-3]:" ; cin>>cheice, switch (choice) ‘ L case 1: v.write to_file (); break; case 2: v.read from file( ); breal case 3: v.append_to_file( ); break? i : ) . } while (choice >0 && choice #nclude"utility-n” class pharma 4 private : int delbit ; // 0: undeleted, 1: deleted char drugcode (5); int batchno; : char category + char uom[4]; float qty: “++ Programmi : (C++ Programming !aresn | lechnolagies 5 public void assign_delbit (int bil void getdata( }7 void showdata( )z int sdelbit( ); . y int pharma :: sdelbit( } { return delbit ; . ’ } void pharma :: assign_delbst( int bit) 4 delbit = pity return; ) void pharma :: getdata( ) ‘ : cout << "\n enter drug code :" ; 5 cin>>drugcode; i cout << "\a enter batch no :" ; cin>batchno; a cout << "\n enter category :" + cimrcategory; + cout << "\n enter unit of measurement :" ; a -in>vuom; . cout << "\n enter quantity produced :" + cin>aty: return; . y ~, void pharma :: showdata( ) y i cout << "\n drug code :" < Af(startpos == endpos) return 0; return (endpos / sizeof (pharma) ); ) void pharma_file :: append( ) —//APP END t ofstream outfile ("PHARMA.txt", ios :: app); char reply 7 do { elrser( ); pharma_buffer.assign_delbit| }; pharna_buffer.getdata( ); outfile.write ( (char*) & pharma buffer, sizecf(pharma) )7 cout<< "\a any more secords [y/n] cin>reply; ) while (reply == ‘y' |! reply == 'Y")+ ourfile. close( 1s void pharma_file :: listall ( ) /fbist ALL : t Afstream infile ("PHARMA.txt") 7 eleser{ )3 int record=1; infile.read ( (char*) spharna_buffer, sizeof (pharma) ) while (infile) i cout << "\n record ro:" <>record_no ; int n=findnorecords( ); if incl) ( message ("sorry ! the data base is empty." return : } if (record non) 1 message ( "record number is out of range"): , modifyfile.open (PHARMA. txt", ios i: in): cout << "\n searching for the record :" <> reply: if (reply == ty" {| reply== ‘y') updatedatabase (seekpas, pharna buffer}: modi fyfile.close( ); void pharma_file :: pelete( } //OELETE( } 4 fstream delfile: int record_n clrser( }5 cout<< "\n enter record no of the record to be delered cinzsrecord_no; int n= findnorecords( 1+ if (nst) ‘ message (” return: , erry | the data base is empty"); C++ Programm 187 Naresh i Technologies if (record_non) Q : message ("yecord number is out of range"); return; : } : delfile.open("PHARMA.txt", dos rz inl; cout << "\n searching for the record :" << record_no; int seekpas = (record_no - 1) * sizeof (pharma) ; delfile.read ( (char*) épharma_buffer, sizeof (pharma) ); , if ( pharma_buffer.sdelbit( ) == 1) ( message ("record not Found"); } delfile.close( ); ‘ return? ) } message ("the record is found"); phazma_buffer-showdata( ); : char reply; cout << "\a wanna delete the record [y/n] :" cin>>reply; 3 if (reply WI reply== 'Y") : i : pharma_buffer.assign_delbie(1); updatedatabase(seekpas, pharma_buffer) ; » ) delfite. close( ); ) void pharma file :: query( ) QUERY l int record _nor ‘ cout << "\A enter record no Gin>>record_no int n-findnorecords ( }; Lf (nc) i { message ("sorry ! the database is empty." ); ) Lf (record_non) : { message ("record number is out of range"); return; ) int seekpas = (record_no) * sizeof (pharma) ; ifstrean queryfile("PHARMA. txt") ; queryfile. seekg(seekpas): : gueryfile ‘read ( (char*) &Pharna buffer, sizeof(pharma) ); if (pharma_buffer.sdelbit( )==1) { message( “record not found"); ie queryfile.close( }; return; ) CH Programming 158 iaresn 1 1echnoloaies message ("the record is found" )7 pharma_buffer.shoudata( )7 getch(); queryfile.close( }+ , void main( ) { pharna_file €ileobi; int choices do 1 clrser( ) cout << "\p main menu" 7 cout << "\n t,add a record\n 2.1ist all records\n 3.modify a record\n 4.deleve a fecord\n 5.query a record\n O.exit\n enter your ehoice[0-5) #7 cin>>choice: switch (choice) q case 1: fileobj.append ( ); break? case 2; fileobj-Listall( 1; break: case 3: fileobj.modify( ); break; case 4: fileobj.Delete ( }; break; case 5: fileobj.query( ); break; ) } while (choice >0 4& choice<6); ) // utility. void message (chaz t + msg) gotoxy (1,2 3); delline( 3; text color (RED) ; © printf (msg); gotoxy (10, 24); text color (GREEN) ; © print£ ("PRESS ANY KEY TO CONTINUE."); geten( ); text clor (WHITE); cbrser( 1; INTEGER INPUT / OUTPUT = * The read( ) and write() member functions are available to work with number. *® The read{ ) and write( ) member functions have to be called with two arguments, 1) the address of the buffer into which the file is to read or write 2) the size of the buffer ++ Pi = CH Programming Naresivi Technologies Syntax: . ( (char*) & buffer, size of (buffer) ); ‘the address of the object has to be type to a character pointer, as compiler assumes the buffer is of character type. . FILE OPENING AND CLOSING = file stream class open() member function can be used to open files. The stream class close() member fimction can be used to close files. Ifa file has to be used for both input and output, explicit open mode bits have to be applied, Each stream has a series of operations or flags associated with its operations. The bits are defined in ios class and some are used for formatting input and output, and some for error handling. he sa te ‘© The bits are enumerated as constants in the class ios. oo bee Syntax: (“filename”, ios :: ! ios :: ERROR HANDLING : The ‘! Operator: ‘The ! operator is overloaded in the ios class. % Itretums a non-zero value if the state of the stream in not good. “The ! operator checks for all possible error states: The Stream Status Bits : Every streara has a state that indicates if an error has occurred, and what that error is. 4 The C+ VO system maintains status information about the out come of each /O operation. 4 The state is indicated by the setting (0 or 1) of a set of bits, and there bits are defined by the io-state variable defined in the ios class. Bit Diagram: =a orbit Y |________— fait bit Unused |___ a bit nia hard bit oo aa i (C++ Programming Pe eer erage: 1) eaf bit: ~ set when an input stream is at its en. — indicates that no more characters are available for extraction. 2) fail bit: — set when the last insertion or extraction has failed. = this is a recoverable error the stream is still in a unusable state. 3) bad bit: — set when an illegal insertion or extraction is attempted. — the stream is not suitable for further use. — usually set when opening a no-existent file, or seeking when a past EOF has occurred . 4) hard fail: > set when a hardware fail bas occurred. — the error that sets hold fail is usually unrecoverable. * Stream member functions are provided to cheek the current state of status bits for a stream. 1) int good(): : — returns a non-zero value if the stream is okay i.e; if none of the bits are set. — returns a zero if an error has accused. 2) Int bad(): — retums a non zero value if the bad bit or hard fail bits are set. — remus @ otherwise. 3) int eof) : > retums a non-zero value if the eof bit is set — retums © otherwise. 4) int fail() : > retums a non-zero value if the fail bit, bad bit or hand fail bits are set. > retums © otherwise. ‘st C++ Programming Naresh i Technologies 5) int rd staie(): — returns the current value of iostate variable. : 6) void clear (int ef=0) : —> sets the error flags equal to ef. — by default, ef equals zero; which resets all the error bits. FILE POINTERS : % the C++ /O system manages two integer values associated with after. % Get pointer : if specifies where in the file, the next input or read operation will occur. - sb. Pat pointerit specifies where:in thetfile:nextsoutpntoraucitesapecationsuill- cour.” % For every input or output operates that take place; the pointer automatically advances sequentially. 5 © “The seeks(') and fellg() functions allowustorset-and-examine the get pointer 2 ‘The seekp( ) and tell() functions perform the actions on the put pointers. + The above functions allow to access the file in a non-sequential, random mode. + -Alliostream classes can be:repositioned using either the seekg() or the seekp(.) member functions. % The functions move the put and the get pointer to an absolute address within the file or a certain number of bytes form a particular ‘> The tellg( ) and tellp( ) can be used to find out the current position of the file pointer within the file. Syntax: . (offset, reference pointer); — offéet is a long integer specifying the number of byte positions to be moved. — reference point ios : : beg -> beginning of file. ios : : cur ~» current position of file pointer ios : : end > the end of file. ADVANCED CLASSES : The class which contains the object of another is a container class The class where object is an attribute of another class is contained class. An object of the contained class is said to be a ‘part of any object of the container class. ‘The ‘part of relationship is also referred to as a composition relationship. ‘The container relationship brings about reusability of code. i ‘The container class does not have access to the private and protected data of the i contained class Sees ie CH Programming, fyuresin 1 recnnctogies CLASSIFIED CLASS: “> When aclass is defined and declared within another, it is called a nested class “ Nesting should be done only if the enclosing class is the sole user of the nested class. INHERITANCE V/s CONTAINERSHIE ¢ % The relationship between a contained and a container class is referred fo as a composition 5 relationship An object of the contained class is a patt of the container class. : ‘In inheritance the relationship between the derived and then base class is referred to as a ’ ‘kind of relaticaship’ A detived class object is a king of the base class object, 4: The-derivediclass inherits all the protected:and public members.of:the.base.class..- + The derived class has special privilege of-access:to the protected: part of the base class. +. Incontainer classes, private and protected members of the container class remain in accessible to the contained class and vice ~ versa. 4 A contained anda container class have no special access privileges between themselves. 4 Public members of the contained class are accessed by the container class only through > the object of the'contained class. - Class A+ CONTAINED Class { member-1 member-2 ) member-n s , class B > CONTAINER Class : i 1 member-1 Aobj: 2 member-n K GENERIC FUNCTIONS + + They are a mechanism which make it possible to use one function or class to handle many different data types “© We can design a single class / function which operates on many data types, instead of having to crate a separate class/ function for each type. dG 4 When applied with function they are called as function templates. a a C+ Programming Naresh i Technologies FUNCTION TEMPLATES + Disadvantage of overloaded functions: ‘+ Time consuming, as the function body is rewritten for different types. + The program consumes more disk space + Error located in one function needs correction in each function body. Advantages of templates: + Myrovides a way to code reuse ability. % Inheritance and composition provide a way to reuse object code. > Templates provide a way to reuse source code. + They significantly:reduce;source code size and:ncrease.code flexibilityavithout.reducing type safety, + Ina funotion.template a data type can be represented:by.aname-that can stand for any - type. Syntax: templete [name] ( [name] variable-1, [name] varibal-2) t body} ) i * + [name] is known as template argument. ¢ Through tout the definition of the function, wherever a specific data type is declared, we substitute the template argument. Compile Time Issues : “ + Function template doesnot suring the compiler into any real action, except for monitoring it for future use. + suepsustee‘The-compiler-doesmiot-generate any code as-yetbecausedtdocsmotknowasyetwhat data type, the function will be working with. + assnedecThewcodeigenerationtakes.place when the fimetion:s.actnally.calledfrontwithin the program, o + When the compiler sees a function call, it knows the type to use, depending on the arguments and generates a specific version. ‘The above process is often known as instantiating the function template, The compiler generates a call to the newly instantiated function and inserts it ints the code. Templates do not save memory, instead they help in not typing the code again and again. ‘The compiler crates them from the generic version that we pass on to it. ae oe + C+ Programming, fvur ean Heenimorogtes, CLASS TEMPLATES : +> Templates can be extended even to classes. 7 % TheY are generally used for data storage classes (container) 5 + Building a class template is similar to a function template Syntax: template class { by body + The template keyword and send a signal specifying that the entire elass will be a template. * The template argument is used at every place in the class specification when there is a reference to the type. + Function templates instantiate when a function call is encountered, classes are instantiated by defining an object using the template arguments. 3 POINTER TO PONDER : 1) the name of a temptate class is expressed differently in different contents. 2) Care should be taken w.r.t syntax when a member function returns a value of its own class. 3) Template arguments can take default values. 4) Anew template can be inherited from an existing template, 5) Every time we instantiate a template the code in the template is generated a new 6) Templates should be used while creating a type safe collection class that can operate on 5 data type of any type. ‘Femplates-1 # include Finclude template type max (type a, type b) return a>b ? arb; ’ tes C++ Programming, Naresh i Technologies void main( ) ‘ int i, 3; elrser(); cout << "\n maximum of two numbers :"7 . cout << "\n\n enter any two integers :" cin>>ir>d; cout << "\n maximum number is :" <>chl>>ch2z cout << "\n maximum characters :" < Temptate2 : } & include : texplate type sun(type a, int b) y t ) return ath; ) } void main( ) ( y int gs float’ #1, £2; cout << "\n enter any two integers i"; Gin>inaj: : cout << "\n enter any two float cinofio>£2; cout << "\n finding the sum of two integers :*7 cout << "\n sum : ("< “\ # include template < class type > void message( char ‘msg, type £) gotoxy (1,23); delline (); textcolor (RED) : CH Programming 16 e o pe one reer uiuyies coutcemsg<<" | "<aiy cout<<"\n Enter Any Float"; cin>>t; cout<<"\n Enter Your Good Name "; ein>>str; cout<<"\n Calling the Message with Integer message (str, i gotoxy (1,10) ; cout<<"\n Calling the message with float :"; > message(ste, £17 Templete-4 # include ¥ Anclude # include # define N 2 ) class emp ( private : int no; char name(20]; float sab; void accept ( 1; void show( )+ int sno()7 float ssalary( char ‘sname( } CH Programmin; 167 : 7 © void emp ee accept ( ) cout << "\n employee no i"; cout << "\n employee name : cout << "\n employee salary cin>>sal; return ? void emp ::'show () ( cout << “\n displaying the data cout << "\n no :" < int findrecord (emp e{ 1, type n, int choice) ( } for (int ( if (choice ==1) ( if (e[i]. snot) return i; ie ichy i++) + if (choice ==2) i if teld) return if ssalazy{ }=sal ' } return-1; int menut { ' int choice; clrscr( )i cout << "\n query by. cout << "\n l.employee no + cout << "\n 2. employee name cout << "\n 3. employee salary cout << "\n O.exit"; cout << "\n enter your choice [0-3) cin>>choice; return choice; void main( ) 4 emp e(N]7 cout << "\n enter the employee details for (int i=0; i>n; kefindrecord (e, a, 1); break: 7 i CH Programming Naresh i Technologies ~ = case 2: char ch{15); cout << "\n enter the name :"; cin>>ch; kefindrecord (e, ch); break; case 3: float £; : cout << "\n enter the salary :"; cim>t ; kefindrecord (e, f, 2); break: ) if (O=1) e(k).show( 1; geen; } while{choice > © &% choice<4); } ‘Templates # include . # include 4 define NS template class array // Class Template : . ‘ protected : ‘type alNl; \ public = void show( 3; void get); } 7 : template void array :: get( } t for (int in0; icn; i++) ‘ oe cout << "\n enter values for a [("<alils 2 return; template void array :: show( ) ¢ cout.setf(ios:: showpoint); type sum = 0; for (int i=0; icw; i++) o ( cout << "\n a ["ccice"] :" Class newarray ; public arsay { // Template Inheritance public - void get( )7 S void show{ )+ 5 4 template Void newarvay :1 get( ) ‘ cout << "\n Enter your good name = for (int iO; i>alils geten( ); returns } template void newarray :: show( ) ‘ for (int 4-0; Act; itt) cout<>choice; 5 switch (choice) ( an case 1: array obj; ) cout << "\n enter integer values :"; obj.gett + 5 cout << "\n displaying the values obj.show( 17 break; case 2: array objl; cout << "\n enter float values : obj. get); cout << "\n displaying the values obj1-show( ); break: a 7 e C++ Programming ys \ Naresh i Technologie case 3: newarray obj2; obj2. get ( 1; 0b}2. show! }; break: ) } while (choice <0 && choicecé); EXCEPTION HANDLING: + + * * Errors cause the programs to foil or certain conditions that lead to estors. ‘An exceptional condition generated in a program should be handled properly. Exception types: 1) Synchronous Exceptions 2) Asynchronous Exceptions ‘The exceptional handling mechanism in C++-cam handle only synchronous exception. ‘The goal of exceptional handling is to detect and report an “exceptional circumstance” which can assist in taking proper action. ‘The mechanism needs a separate code, with the responsibilities stated as: 1) hit the exception or trace the exception 2) throw the exception or inform about an error. 3) Catch the exception or receive the error info. 4) Handle the exception or take corrective steps. Error handling code consists of two segments, 1),,one to detect the errors and throw exceptions. 2) Second to catch: the exceptions end take corrective nieasures, Syntax: ot Pi i 172 C++ Programming furs) becnnologies Try block ee | nvoxe 5 Invoke a function that cause an [ Throw block : exception function that cause exception Catch Block. eee See 3 THROW Excention Handlers: * ‘> C+ needs throw, try and catch keywords to handle exceptions 3 % The keyword try prefaces a block of statements which may generate exceptions. ; % The catch block defined by keyword ‘catch’ catches the exceptions thrown by throw and wt handles them appropriately ° 4 The“try’ block code normally in values a function that detects an exception. 4 The funetion which is in the “throw” block retums the control to ‘catch’ block which may contain more than one statement, each corresponding to a particular type of reception. Exeeptin-L # include : class some_class (17 void mem_alloc (double *ptr, long unsigned int n) { 3 double a; some_class x; if ((ptrenew double(n]) == NOEL) throw else throw x ; void maint double *v; long unsigned int nr cout<< "\n enter no. of elements + S C+ Programming Naresh i Technologies ) try ( memalloc(y, n); } catch (double) cout << "\n free memory storage unavailable \n" ; , catch (some_class) { cout << "\p memory allocated’ ) Exeeptin-2 #include void fun_one (bool flag) ) cout << "A, 7 try cout << "By fun_two(£lag) + bee MC, catch (int i) { cout << "D, , cout << "E, veid fun_two(bool flag) { cout << "FP, "s try fun_three (flag); ) catch (float £) fl cout << "D, , cout << "Hy i C++ Programming Naresh i Technologies void fun_three (bool flag) 7 t cout << "1, "5 if (flag) ( coutc< "throw" 7 int x7 : throw x7 5 ) else cout<< "no-throw"s cout << "5, "3 - , void main( ) : . { cout<< "\n flag == false fun_one (false); cout << "finished \n"; cout << " \n flageetrue :"; : fon_one (true)? cout<< "finished \n"; Exception-3 ) # include 4 define w 3 class QUEUE . ‘ private int a(N); } int front, rear ; public a ‘QUEUE, }; void add_element (int); int del_element ( ); class overflow{ }7 class underflow! }; 3 void QUEUE.:: QUEUE( } void QUEUE :: add_element (int x) ‘ if (rear==N-1) 4 throw overflow( }+ alrear|=x: Cr+ Progearmin 175 aa Naresh i Technologies front0; int QUEUE, rs t del_element ( ) int dy if (front == -1) throw underflow( }7 dea{front}; mo if (front=srear) front=rear= - 7 else Erontt+; return dy - ) void main( ) i : QUEUE obj; A : try 4 . char reply; do ‘ re Aint num; cout << "\n add a element :"; cin>>num; obj. add_element (num); “ cout<< "\n any more. [y/n] :"; cin>>replys - while (reply == 'y' II reply== ty"); = catch (QUEUE : :over flow) ‘ ‘ cout<< “\n queue is full \n cannot edd any m « ) a By eee ae while (reply== 'y' || reply == 'y') ‘ : oo int num: nin 2'3b). del_elemontt 32 ; : oo } catch (QUEUE : : underflow) C i i cout<< "\n queue is empty \n cannot proceed further..!"; } a 7 i (C+ Programming Naresh i Technologies Exception ~4 4 include class dividebyzero{ }7 void main( } ( : float numer, denom; , cout << "\n enter the numerator :" ; cin>>numer; cout << "\n enter the denominator :" ; cin>>denom; try ( 7 4£ (denom == 0) t dividebyzero d: a throw di 1 cout<< "\n result is :"

You might also like