Open navigation menu
Close suggestions
Search
Search
en
Change Language
Upload
Sign in
Sign in
Download free for days
0 ratings
0% found this document useful (0 votes)
1K views
178 pages
Naresh C++
Uploaded by
krish krishna
AI-enhanced title
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
Download
Save
Save NARESH C++ For Later
Share
0%
0% found this document useful, undefined
0%
, undefined
Print
Embed
Report
0 ratings
0% found this document useful (0 votes)
1K views
178 pages
Naresh C++
Uploaded by
krish krishna
AI-enhanced title
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
Carousel Previous
Carousel Next
Download
Save
Save NARESH C++ For Later
Share
0%
0% found this document useful, undefined
0%
, undefined
Print
Embed
Report
Download
Save NARESH C++ For Later
You are on page 1
/ 178
Search
Fullscreen
C++ Course Material Ni Granesto | technologies Opp. Satyam Theatre, Ameerpet, Hyderabad - 500 016. PAT TPENaresh 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++ Programmingay 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++ ProgrammingNaresh 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++ ProgrammingNaresh 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++ ProgrammingNaresh 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++ ProgrammingNaresh 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+ ProgrammingNaresh 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++ ProgrammingNaresh 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++ ProgrammingNarech 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++ ProgrammingNaresh 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+ ProgrammingNaresh 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 ProgrammingOPERATOR 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++ Programmingx=; ?* 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++ ProgrammingNaresh 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 1BNaresh 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, 28cmatb; 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 ProgrammingNaresh 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¥+ ProgrammingNaresh 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 Programmingcout << "\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 Programming7) 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¥+ ProgrammingNaresh 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 38Naresh 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++ ProgrammingNaresh 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++ Programming7 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 42INaresn | 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¥+ ProgrammingNaresh 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+ ProgrammingNaresh 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¥+ Programmingvoid 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++ ProgrammingNaresh 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++ Programmingvoid 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+ ProgrammingNaresh 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+ ProgrammingNaresh 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++ ProgrammingNaresh |! =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 grammingNaresh 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+ Programming4 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 aNaresh 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+ ProgrammingNaresh 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+ ProgrammingNaresh 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++ ProgrammingNaresh 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 Programming7 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++ ProgrammingMemory 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 ProgrammingNaresh 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++ ProgrammingNaresh 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++ ProgrammingNaresh 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++ Programmingint 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 Programmingvoid 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#+ ProgrammingNaresh 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++ Programmingeeshow ()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+ ProgrammingFinclude
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++ ProgrammingNNaresn 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+ Programmingpublic: 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++ Programmingvoid 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 Programmingclass 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 ProgrammingNaresh 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+ ProgrammingNaresh 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+ ProgrammingNaresh 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-07ctr
draw(); break; case case ! geten(); } ((ellipse*) £{etr])->draw(); breal H+ i 15 C+ ProgrammingNaresh 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++ Programmingiaresn | |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;ctr
draw() 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++ Programmingvoid 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+ Programmingvoid 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 ProgrammingNaresh 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 iatNaresh 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+ Programmingclass 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+ Programmingryuresn 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++ Programmingfinclude
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 ProgrammingNaresh 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++ Programmingv 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++ Programmingyee 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++ Programmingsw 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 ProgrammingNaresi 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" <
> (istream &s, date sa) t cout << "\n enter the date in dd mm yy :"; s>>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¥ Programmingiuresn | 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 Programmingpublic = 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 eeNaresh 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++ ProgrammingNaresh 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+ ProgrammingNaré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+ ProgrammingNaresh 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 eeeNaresh 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++ ProgrammingNaresh 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+ Programmingvoid 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<