You are on page 1of 236
4 Text Book OF ‘ OBJECT ORIENTED PROGRAMMING USING oe (22316) Semester - Ill SECOND YEAR DIPLOMA IN COMPUTER ENGINEERING AND INFORMATION TECHNOLOGY GROUP. As Per MSBTE's ‘I’ Scheme Syllabus Prashant Jawalkar Mem Assistant Professor, Dept of Computer Engg. JSPM's Bhivarabai Sawant Institute of Technology & Research (8SIOTR) ‘Waghol, PUNE Anand Aware ME (Comp) Sr. Lecturer in Computer Engg, Department ‘Vidyavardhini's Bhausaheb Vartak Polytechnic Vaal, MUMGAT Price % 185.00 epee ee ISecondEdiion : July 2019 2 Authors he tei of this pbaton or ry part theeo shoud not be repre or anemite n any form oy sred in any computer storage system or device fy Hiaaees Sung potcapy reset, pig or formants stm or repceuced on on Si ape, peoreee medio ehrineraton sori Jar ctnout writen pemision cf utr with whom the fights re eave Breach of is cnn abl fog ecto, Jere ta been made fo mele wor or omit in his pubestn 19 se of hs elo may have cept ay mistake, eo: or deepen 0 Wacted Snel be bought to ur ote Sat Se tten cae of nf net ection Is ote that nate: the publther ror he author cr seers Oe panel ay droge ole of acon anyone, Lid nay mennet, thereto [Published By Polyplate Printed by 5 INIRALI PRAKASHAN YOGIRAJ PRINTERS AND BINDERS| |Abhyudaya Pragati 1312, shiva Nagar ‘Survey No 10/14, Ghule industria Estate| fof LM. Road, PUNE— 411005 Nanded Gaon Road| [rel - (20) 25512336/37/29, Fax (020) 25513379 Nanded Pune ~ 411083 Email rirlipune@pragationlinecom Mobile No, 9404733083/9850046517 i > DISTRIBUTION CENTRES : PUNE i Nirali Prakashan + 129, udhwer Pet, ogushwari Mani Lane, Pune 41002, Mahareshis {For orders within Pune) Tel: (020) 2445 2046; Mobis : 9657702165 Email: ricallocal@pragationine.com Nirali Prakashan + S.No 28/27, Dhayari Nes Asan Colege Pune 411042 (For orders outside Puna} Tel: (020) 24690204; Mobile: 9857703343 mall: bookorder@pragationine.com MUMBAI 385, SVP. Road, Rasdhara Co-op. Heg. Society Ltd Giegaur, Mami 400004, Maharashtra; Mobil: 9320129587 : Tel: 022) 2385 6339 / 2386 9976, Fax: 022) 23869975 Email: nrsimumbai@pragaonine.com > DISTRIBUTION BRANCHES JALGAON Niroli Prakashan + 34,V. V, Gola Market, Navi Peth Jalgaon 425001, Maharashtra, Tel: (257) 2220395, Mad: 84234 91850; Email: nalalgson@pregatoniinecom KOLHAPUR | Nirali Prakashan: New Mahadver Rosd, Keder Plaza, 1" Floor Opp. 1D Bank, Kolhapur 416 012 Maharactra Mob : 9850046155; Ema: riralkePapur@pregationine.com- NAGPUR Niralt Prakashan: Above Meratha Mandi, Shop No. 3, Fist Heer, Rani Jhanehi Square, Stabul, Nagpur 440012, Maharashtra ‘Tel: (0722) 254 7123, Emal:neanagpurepragationine com DELHI! Nirali Prakashan “: 4593/15, Basement Agarwal Lane, Anse Read, Dary3920) ‘Near Times of India Builsing, New Delhi 210002 Mob: 08505972553 all: niralidelni@ pregationine com BENGALURU Mais Ground Foor, Jaya Apartments, No. 98, 6 Cross. Mein, Melleswaram, Bengalurs$60003, Kemataka Mob 49003034 nail nalbengalore@ pragationlinecom (Other Branches : Hyderabad, Chen. Nirall Prakashan Niralt Prakashan Note; Ever pole af tes been made to aad errs ramislon is book Inept hi, eos may have eeptin. Ary pect ero of isa so nce oct shal be ous curnote, shal be sen caroline ext edn. lle noted rat nether the pula, othe ato bok seer salle respons or any dage oven fasten By ono ary Kh 2 manrr, rear. Th coder must ces check lh fats an cortets wih re Goverment rotcaton or pleats sms resem sneer oe * First chapter gives principle of Object Oriented Programming. This chapter also’ gives on introduction of C++ language, are also explained in this chapter, * Third chapter covers th * Fourth chapter introduces pointers and polymorphism concepts of C++, Various types of polymorphisms ore also explained in this chapten * File operations in C++ are covered in fifth chapter. A special words of thonk to Shri, Dineshbhai Furia; Mr, Tignesh Furic for showing full faith in us to nrite this text book, We also thank to Mir. Amar Salurkhe and ‘Mn. Akbar Shaikh of M/s Nirali Prakashan fur their excellent co-operation, We also thank Ms. Chaitali Takale, Mr, Ravindra Walodare, Mr. Sachin Shinde, Mi. Ashok Bodke, ‘Mr. Moshin Sayyed and Mr. Nitin Thorat, ; We welcome constructive suggestions from our colleagues and students, Authors os0 Syllabus ... 1 12 13 14 16 16 17 22 23 24 25 Procedure Oriented Programming (POP) verses Object Oriented Programming (OOP) Basic Concepts of Object Oriented Programming, Object Oriented Languages, Applications of OOP C verses C++, Structure of C++ Program, Simple C++ Program Tokens, Keywords, Variables, Constants, Basle Data Types, User-defined Data Types, Typecasting, Operators, Expressions Control Structures: Decision making Statements and Loops ‘Scope Resolution Operator, Memory Management Operators Arrays, Strings and Structures in C++ Class and Object: Introduction, Specifying a Ciass, Access Specifiers, Defining Member Functions, Creating Objects, Momory Allocations for Objects Static Data Members, Static Member Function, Friend Function Array of Objects, Object as Function Arguments Concepts of Constructors, Types of Constructors Muttiple Constructors in a Ciass, Constructors with Default Arguments Destructors 2 tng seg vines Sabana Introduction to Inheritance, Defining a Derived Class, Visibilty Modas and Effects ‘Types of Inheritance: Single, Muttievel, Multiple, Hierarchical, Hybrid Viral 8as0 Class, Abstract Class, Constructors in Derived Class om 52 ‘ 53 | \ | Bie teins abscess { | | | | | 1 | Concepts of Pointer: Pointer Declaration, Pointer Operator, Address Operator, Pointer Arithmetic Pointer to Object: Pointer to Object, this Pointer, Pointer to Derived Class Introduction to Polymorphism, Types of Polymorphism Compile-time Polymorphism: Function Overieading, Operator Overloading, Overloading of Unaty and Binary Operators, Rules for Operator Overloading Run-time Polymorphism: Virtual Functions, Rules for Virtual Funct (C++ Stream Classes, Classes for File Stream Operations Opening Files, Closing Files, Reading from and Writing to Files Detection of End of File, File Modes 10 14 12 13 14 16 16 17 Introduction Procedure Oriented Programming (POP) Vs object oriented programming (OOP) 4.4.4 Prosedure Oriented Programming (POP) 4.4.2. Object Oriented Programming (OOP 4.1.3 Object Orionted Programming (OOP) Vs Procedure Oriented Programming (POP) Basio Concepts of Object Oriented Programming 1.2.1 Objects 1.22 Classes 4.2.3 Data Encapsultion and Abstraction 4.2.4 Inheritance 4.2.5 Polymorphism 1.2.6 Dynamic Binding 1.2.7 Message Passing 1.2.8 Object-Oriented Language 4.2.9 Applications of OOP Introduction to C++ 1.8.1 Evolution of ++ 1.92, Features of C++ 193 CvsC+ 1.9.4 Structure of C++ Program Basios of C++ 1.4.1. Character Set 4.4.2. Tokens in C++ 1.4.3 Keywords 1.4.4 Identifiers in C++ 4.4.5 Variables in C++ 4.4.5.1 Declaration of Variables 1.4.5.2 Initialization of Variables 1.48 Constants 4.4.7 Data Types 1.4.8 Operators in C++ 1.4.9 Expressions 1.4.10 Typecasting Control Structures: 1.8.1 Conditional / Decision Making Statements 1.5.2 Loops ‘Scope Resolution Operator (:) and Memory Management Operaters ) 1.6.1 Scope Resolution Operator 1.6.2 Merory Management Operators Arrays, Strings and Structures in C++ 171 Arrays 4.7.4.1 Single-Dimensional Array 47.4.2. Mult-Dimensional Array 1.7.2 Strings 1.7.2.1 Strings (Array of Characters) 1.7.2.2 String Class in O++ 1.7.23 Manipulating Strings 1.7.2.4 Array of String 1.7.3 Structures 171 1.7.3.1 Defining Structures 474 1.78.2 Declaring Structure Variables 1.72 1.7.3.3. Initializing 9 Structure 172 1.7.8.4 Accessing Structure Members 172 1.7.3.5 Nested Structures 178 1.7.36 Array of Structures 1.76 «Practice Questions 1.78 + MSBTE's Questions & Answers ~ 79 2.0 Introduction 2A 24 Introduction to Classes and Objects 24 24.1 Specifying a Class 2A 2.41.2 Objects (Creating Objects) 23 2A.8 Access Spootiers 25 2.1.4 Defining Data Members and Member Function 28 2.1.5 Memory Allocation of Objects 2.10 22 Static Data Members, Static Member Function and Friend Function 2.10 2.2.1 Static Data Members 2:10 t 2.2.2 Static Member Functions 242 : 225 Friend Function 213, i 29 Array of Objects and Object as Function Argument 215 i 23.1 Aray of Objects 215 2.82 Object as Function Arguments 223 24 Concepts of Constructor 224 24.1. Types of Constructors 227 2.4.1.1 Defauit Constructor - ' 2e8 24.1.2 Parameterized Constructor a) 220 2.4.1.3 Overloaded or Multiple Constructor 231 2.4.1.4 Constructor with Defauit Arguments 233, 2.4.1.8 Copy Constructor 2.34. 2.4.1.8 Dynamic Constructor 2.36 25. Deswuctors 2.38 + Practice Questions eat + MSBTE's Questions & Answers 241 3. Extending Classes wsing Inhevitaneo =) nT SHES) 3.0 Introduction 34 3.1 Introduction to Inheritance 3a 3.1.1. Defining Derived Classes 33 3.1.2 Visiblity Modes and Effects 34 i 31.2.1 Public Visibilty Mode or Public Inheritance 34 i 3.1.2.2 Private Vieitilty Mode or Private Inhertance 35 } 3.1.2.3. Protected Visibilty Mode or Protected Inheritance 36 | 82 Types of inheritance 38 32.1. Single Inhertance 39 3.2.2 Multilevel inheritance at 32.3. Multiple Inheritance 3.13, 3.2.4 Hierarchical Inheritance 345 8.2.5 Hybrid Inheritance 3.18 83° Virtual Base Classes, Abstract Classes and Constructors in Derived Class 9.3.1 Virtual Base Classes 3.3.2 Abstract Classes 7 3.3.3 Constructors in Derived Classes * Practice Questions * MSBTE’s Questions & Answers 40 Introduction 4.1 Concepts of Pointer 4.11 Pointer Deciaration 4.12 Pointer Operators 4.1.3. Pointer Arithmetic 42. Pointer to Objacts 4.2.1. this Pointer 4.2.2 Pointer to Derived Classes 4.3 Introduction to Polymorphism 4.3.1 Typos of Polymorphism 44 Compile-Time Polymorphism, 4.4.1 Function Overloading 44.2 Operator Overloading 4.4.3 Overloading of Unary Operators 4.4.4 Overloading Binary Operators 44.8. Rules for Overloading Operator 4.5. Run-time Polymorphism 4.8.1 Virtual Functions 2. Rules for Virtual Functions 3 Pure Virival Function Practice Quéstions MSBTE's Questions & Answers 5.0 Introduction 5.1 C++ Stream Classes and Classes for File Stream Operations 5.2 Opening Files, Closing Files, Reading from and Writing to Flas 5.2.1, Opening and Closing a File 52.1.1. Opening Files 52.1.2 Closing File 5.2.2 Reading from and Writing to Files 5.3 Detecting the End-of-File 54 File Modes * Practice Questions ‘© MSBTE’s Questions & Answers Write simple C++ program for solving the given expression using POP approach. Write OOP based C++ program using decision making and loop structure for the given situation. @©_ Write OOP based C++ program using arrays to solve the given problem. G_ Use the structure in C++ program for solving the given problem. Tc understand Basic Concepts of OOP and POP Te learn Concepts of C++ B_ To study Tokens in Cre © Tounderstand Control Structures in C++ To learn Operators in C++ To study Arrays, Strings and Structures in C++ + Computers are designed to follow instructions. A computer program is a set of instructions that tells the computer how to solve a problem or perform a task. + Programming refers to the method of creating a sequence of instructions to enable the computer to perform a task, It is done by developing logic and then writing instructions in a programming language. In short, a programming language is a language used to write computer programs. * During the last fow decades, the increasing complexity of software system is due to the increase in the user requirement. To build today's cornplex software, it is just not enough to put together a sequence of programming statements and sets of procedures and modules, we need to incorporate sound construction techniques and program structures that are easy and simple to comprehend, ‘implement and modify. + Since, the invention of the computer, many programming approaches have been tried and the primary motivation in each has been the concern to handle the increasing complexity of programs that are reliable and maintainable, These include following techniques have become popular among ‘computer programmers over the last two decades. These techniques are: 1, Modular Programming: It emphasizes separating the functionality of a program into independent, interchangeable modules, such that each contains everything necessary to execute only one aspect of the desired functionality. Examples: Ada, Algol, C#, COBOL. ete. a) ES SRR RTA SAGA SSR STSCI | | ‘Object Oriented Programming Using C++ 12 Principle of Object Oriented Programming 2. Top-down Programming; It focuses on the use of modules. The program is broken up into small modules so that it is easy and simple to trace a particular segment of code in the software Program. The modules at the top level are (main module) those that perform general tasks, and those at the lower level (sub-ordinate modules) perform specific tasks. Each module in this appreach is based on the functionality of its functions and procedures and the pr. gramming begins from the tep level of hierarchy and progresses towards the lower levels, Exa:nples: C+s, Javaetc. 3. Bottom-up Programming: It refers to the style of programming where an application is constructed with the description of modules, The description begins at the bottom of the hierarchy of modules and progresses through higher levels until it reaches the top, Example, 'C. 4. Structured Programming: It is concerned with the structures used in a computer program, Generally, ‘structures of computer program comprise decisions, sequences and loops, Examples: Pascal, PL/Tete. * With the advent of languages such as C language, structured programming beceme very popular in the year 1980s. Structured programming was a powerful tool that enabled programmers to write ‘moderately complex programs fairly easily and simply. However, as the progrems size grew larger, even the st-ctured approach failed to show the desired results in terms of easy-to update, bug-free, easy-to maintain, and reusable programs. ; * OOP (Object Oriented Programming) is an approach to program organization and development that attempts to eliminate some of the pitfalls of conventional programming (structured) methods by Incorporating the best of structured programming features with several powerful new concepts. * OOP is a new way of organizing and developing programs and has nothing to do with any particular language. In this chapter we study various concepts of OOP. PoP and OOP both are programtning approaches used for computer programming, These approaciies in technical terms are known programming peradigms. #] Procedure Orienved Programming (POP) * Procedure Oriented Programming (POP) is the traditional/conventional way of programming, where ‘an application problem is viewed as a sequence of steps (algorithms). * The conventional pogramming, using High Level Languages (HiLIs) such as C, COBOL, FORIRAN and PASCAL are commonly known as Procedural Oriented Programming (POP) languages * InPoP, the problem is viewed as a sequence of things like reading, printing, calculating and so on. In other words, using programming procedure oriented approach the computer programmer views a problem as asequence of things to do. * Aprogram in a procedural language is a list/eet of instructions, In POPs, prograins are divided into different procedures (also known as functions, routines er sub-routines} and each procedure contains a set of instructions that performs a specific task, * In POP each function has a clearly defined purpose and a clearly defined interface to the other functions in the program. A number of functions can be grouped together into a larger entity called amodule. | Object Orient Progeammiig Using C++ 4a Principle of Object Orionted Programming | © programs in POP consist of a controlling function known as the main, which controls the execution of other functions. When a call toa function is made, the program control is passed on to that function and all the instructions in that function are executed one | after the other. After executing all the i instructions, the program control returns to s ‘he function from where the call is made ¢ Fig. 11 shows typical program structure of PoP. Fig, 11: Typical Program Structure of Procedural Oriented Programming (POP) Language % © A program in a POP language is nothing but a set of functions, Each function has a well-defined purpose and a well-defined interface to other functions. 1 * A function in procedure oriented ue programming language can have its ; ‘own data known as local data and multiple functions can access the same data known as giobal data. © structured programming (also known t as procedural programming) was a [/fesibaal| [ftesibel] [plesipst abe ‘a powerful and an easy approach of ‘Relationship among Functions in Procedure-oriented. writing programs. Programming language Characteristics/Features of Procedural Oriented Programming (POP): 1. In POP, the application programs are organized, designed and written around the procedures, making the structured programming procedure centric. 2. More emphasis is laid on procedures or algorithms (doing things) rather than data. 3. In POP, data moves openly around the system from function to function because of global data is shared. 4, Functions in POP transform data from one form to another form. Large programs in POP are divided into smaller programs known as functions (modules). 6. Procedure oriented programming language uses top-down programming approach in program design. Advantages of POP: 1, It¥s easy and simple to port programs as compilers for procedure languages are easily available. 2. POPis easy way of writing programs. Disadvantages of POP: 1. POP does not model real world problems. . 2, ‘The large programs developed using POP are difficult to maintain, modify, debug and extend. 3, Procedure oriented programming languages allows data to move freely from one function to another without any security. - Object Oriented Programming (00P) * To ovércome the limitations of POP, Object Oriented Programming (OOP) paradigm has been developed which has revolutionized the process of software development. * OOP not only includes the best features of structured programming but also includes some new and” LY. powerful features which helped in the development of well-designed high-quality software, a ee \y E=- ‘Object Orlented Programming Using C++. 14 Principle of Object Oriented Programming ‘The. main idea behind OOP languages is to encapsulate both data and functions (operations) that operate on these data into a ‘meaningful unit known as an object. In an OOP environment, data is considered as a critical element and is tied to functions that operate on it. A set of data that is encapsulated in an object is known as the member data and the functions that operates on these data are known as the member functions. ‘The organization of data and function in object-oriented program is shown in Fig. 13. ‘The data of an object can be accessed only by the functions associated with that object. However, functions of one object can access the functions of other objects. a Some of the Characteristics/Features of object oriented programming languages are given below: ee] 1. 1n OOP, the application programs are organized, designed and written around the date, makir.g object oriented programming data centric. 2. Unlike POP, more emphasis is laid on data rather than procedures or algorithms. 3, OOP uses bottom-up programming approach for program design. ‘4, Data and its operations in OOP are bound together into objects. 5, In OOP, objects can communicate with each other through message passing. 6. In OOP, data is hidden and cannot be accessed by external functions. 7, 1nOOP, data structures are designed such that they characterize the objects. Object oriented programming language is very useful in application areas like real-time, artificial intelligence, expert systems, computer-aided manufacturing/designing, office automation and decision support systems, Advantages of OOP: ‘L Reusability of the code is the main advantage of OOP, Redundant code can be eliminated through inheritance feature of OOP. 2. The programs and data are more secure due to data hiding feature of OOP. 3. In OOP, a program can easily be broken down into objects, which truly mode! the real world objects. New data types can be easily created through data abstraction feature of OOP. Disadvantages of OOP: ‘L all languages cannot easily implement object-oriented approach. So, OOP is limited to a few languages, (object-oriented languages). First time development process in OOP is more difficult than procedure oriented software, Object oriented progr Procedural programming language; object oriented. oriented. = 2; __| OOP trace on data, ‘POP trace on procedures. 3 | 00? follow top-down approach in program | POP follow bottom-up approach in program design. design. ‘contd. .. PT RANI be SS i | | imma ‘object Oriented Programming Using C+ 48. Principles of Object Oriented Programming ‘4, | Basic building block of OOPis object.1n OOP | Basicuilding block of POP is function, In program is decomposed intoa numberof __| POP program is Cecomposed into a number mesningful units know as objects. of functions or procedures. 5. | In OOP object is collection of data and InPOP function is a collection of instruction members. that performs a specific tasks. 6. _ | In OOP, importanceis given to the data In Por, importance s not given to data but to rather than procedures or functions because | functions as well as sequence of actions to be itworks as a real world. done. 7. | OOP prevides data hiding so provides more _| POP does not have any proper way for hiding security. data soit isless secure. 3. _ | Examples of OOP includes C++, JAVA, Examples of POP includes C, VB, FORTRAN, VANET, CH.NET, ete. COBOL, PASCAL ete, 3 9. | moor, objects communicate through 1m POP functions communicates each other member functions. through arguments. 10. | OOP is an data centric language. | POPs procedure centric language. ‘+ QOP is the most recent concept among programming paradigms today and defined as, "an approach that provides a way of modularizing programs by creating partitioned memory area for both data and functions that can be used as templates for creating copies of such modules on demand." ‘+ To understand the concept of OOP, it is necessary to know the fundamental terms and concepts of ‘this approach, includes objects, classes, data abstraction, encapsulation, inheritance, polymorphism, message passing and so on. ‘* Objects are the basic run-time entities in an OOP environment. Any real world object can be treated asan object in the GOP, such as a car, a person, a university buildings, a table, a computer etc. * An object is an instance of a class. An object consists of two characteristics namely, state (attribute) and behaviour (operation). The state of an object is one of the possible conditions that an object can exist in and is represented by its characteristics or attributes or data while the behaviour of an object determines how an object acts or behaves and is represented by the operations that it can perform, + In OOP, the attributes of an object are represented by the variables and the operations are Tepresented by the functions. Fig. 144 shows two notations for representation of an object that are popularly used in object oriented environment. @ ®) Different style of Representing an Cbject, Object Orlented Programming Using Cr+ 18 a “1. Data Encapsulation Prinsiples of Object Oriented Programming @) (i) Representation of different objects in cifferent Ways Fig.14 Classes. Tn OOP, a class is a way of grouping objects having similar characteristics. A class is a user-defined ata type, which represents a group of similar objects. 4 class provides a template or plan or blue prints to create objects of particular type. To create an object of a particular class, we need to specify the data member and member function of that particular class. Fig. 15 (a) shows class Person with data members Name, Age, City and Phone with display (member function), while Fig. 15 (b) shows objects of class Person, (@) Class Definition (Person) (0) Objects of Class (Person) Fig. 1.5: Instance of a Class Boy ie, Objects “An operation required for an object or entity when coded in a class is called as a method. Data Encapsulation and Abstraction It is the most striking feature in OOP. Encapsulation is the technique of binding the data and the functions (that operate on them) ina single unit called a class. Encapsulation is the way to implement data abstraction in OOP, A well-encapsulated object acts as a "black box’for other parts of the program ‘e,, it provides services to the external functions or uther objects that interact with it. However, these external functions or the objects do not need to know its internal details. For example, in Fig. 1.6 the data p_ID, p_name, price and qty_in_stock and the functions display-product) and check stock. are ‘encapsulated in a class Product. in OOP, the hidden data of a class cannot be accessed directly by the outside world, ‘however, the member functions of the class act as a medium to access the hidden data, This process of preventing the data from the direct access by the external functions is called data hiding. In short, the wrapping up of data and functions intoa single unit ie, class is called as, encapsulation, Fig. 16: Class and ito Objects ess SomeoMMRER CE CasSERS sim Nt (a Wageeties 72a aa OMR NE MERE Object Oriented Programming Using C++ 7 of Object Oriented Programming 2. Data Abstraction: ‘+ In 002, each object will have external interfaces through which it can be used. There is no need to look into its inner details, So the user needs to know the external interfaces only, to make use of an. object. ‘* The internal details of the objects are hidden which makes them abstract, This technique or feature of hid.ng internal details in an object is known as data abstraction. + Abstraction is the selective examinaticn of certain aspects of a problem, The goal of abstraction is to isolate those aspects that are important for some purpose and suppress those aspects that are unimportant. + Many different abstractions of the same thing are possible, depending on the purpose for which they are made, In other words, we can say that abstraction as the act of representing essential features without including the background details or explanations. + Data abstraction is the process of defining a data type, often called Abstract Data Type (ADT), together with the principle of data hiding. Inheritance + The ability of object of one class to acquire the characteristies/properties of objects of another class is known as inheritance, The existing class is known as base class and the new class derived from the ‘ oxisting class is knovm as derived class + + Through inheritance feature in OOP, it is possible to utilize the details of an existing class without i repeating the details of base class again in derived class and, hence, it provides the advantage of reusability and saves development time. + In Fig. 17, Course is the base j class from which two classes Non-professional Course and i Professional Course are derived, 1 ‘The courses BA, B.Sc and B.Com } cea SARE ets cA are the classes derived from non-professional course while, BE and MBBS, MBA courses are derived from professional “J course, Fig. 17: Inheritance in Object Oriented Programming’ * Inheritance can be of five types, namely single inheritance, multilevel inheritance, multiple inheritance, hierarchical inheritance and hybrid inheritance. EEE roiymorphisin isi) * The concept of polymorphism plays an important role in OOP as it allows an entity to be represented in various forms, In the term polymorphism, ‘poly’ means many and ‘morphism’ means form, so polymorphism means having many (multiple) forms. Polymorphism is the ability of an entity such sa function or a message to be processed in more than one form, + In C++, polymorphism can be achieved either at compile-time or at run-time. At compile- time, polymorphism is implemented using operator overloading and function over- loading. However, at run-time, polymer-phism is implemented using virtual functions as shown za in Fig. 1.8. Fig. 1.8; Types of Polymorphism preseason 10 Principles ef Object Orlented Programming ‘Object Orlented Programming Using Cr+ «Compile-time polymorphism is the linkage of function call to the actual code of the function is done at compile time itself. The process o instances is known as operator overloading. Usin: of tasks is known as function overloading. © Consider Fig. 19 in which three different classes, Circle, Rectangle and Triangle are derived from the base class figure. The function draw) of the base class is implemented in different ways in all its derived classes and a call to @ particular function is determined at run-time. This form of polymorphism is called run-time eae) polymorphism (See Fig. 19). i Dynamic Binding ‘- _ Binding refers to the linking of a procedu Dynamic binding, also called as late binding, call is not known until call at run-time. «Cet language implements dynamic binding through the use of virtia) functions. The function calls l esolved at run-time are somewhat less efficient than function calls resolved at compile-time. the process of linking a function call to the actual code of the furtction at run- ‘known to the compiler until run- f making an operator to exhibit different behaviours in different ga single function name to perform different types re call to the code to be executed in response to the call ‘means that the code associated with a given function | cot tn SNES RENN RRR ERE REE = Dynamic binding is ‘dime Le, in dynamic binding, the actual code to be executed is not ti BRT] Message Passing ‘© An OOP consists of a set of objec cts and these objects communicate with each other. Message passing fea process by which different objects ina program interact with each eit ie, when the program eared, te objects interact or communicate with each other by.sending and yeceiving messages. | «The messages in OOP are exchanged by calling a ‘the member functions of the classes. In OOP, the Object » Display (argument) i | | snes of programming involves the following | i seep Object I Step 1: Create classes for defining objects and . | their behaviours. Ccornmuricaion Operator . | Message Data l step2 : Declare the required objects. i ‘step3 : Establish communication among objects Wi ‘through message passing. ‘Fig. 4.10: Message Passing Concept in OOP coe Mh «message in OOP for an object is interpreted as a request for the execution of a function. A required function is invoked ject Message Information i Aner receiving the message and the desired results are | | | generated within an object. j ‘ « Amessage in OOP comprises the name of the object, nameof empioyea asin (orm | the function and the information to be sent to the object in Hig i ee ee in i ‘the form of arguments to the function, as shown in Fig, 1.1. . nFig. tt, employees treated as an object sending the message #8187) find the salary secured by ihe employee with the specified emp.id. In this case, @ function calles salary() is treated as a Tnessage and a parameter emp jd treated as information passed fo the object. cng object Oventad Programming Using C++ 19 Principles of Object Oriented Programming ne Object-Oriented Language ont Depending on the object features supported by the languages are classified into two categories namely, Object-based programming language and Object-oriented programming language, Object-based Programming Languages: These languages support encapsulation and object identity without supporting important features of OOP languages such as polymorphism, inheritance and message-based communication. ‘Ada and Modula-2 are examples of object-based programming languages. In short, Object-based Language = Encapsulation + Object Identity. Object-oriented Programming Languages: ‘The high-level language that implements the Object Oriented (00) concepts like encapsulation, data hiding, operator overloading, etc. is known as an object-oriented language (also called an 00 : language). | © Object-oriented ianguages incorporate all features of object-based programming languages along pes with inheritance and polymorphism, Therefore, an object-oriented programming language is all. defined by the following statement: ica Object-oriented Language = Object-based Features + Polymorphism + Inheritance © © Depending on the extent to which they support Object Oriented (00) concepts, the Object Oriented ls (00) languages are classified into following several categories: = () Pure Languages: Languages that not only support but also enforce all object-oriented concepts are called pure object oriented languages. In pure object-oriented languages, everything from Be character and punctuations to modules is treated as an object. Smalltalk, Eiffel and Ruby'are ~ examples of pure object-oriented languages. (i) Multi-paradigm Languages: Languages that support many programming paradigms like procedural programming, generic programming, etc.,one of which is object-oriented paradigm. ae. are called multi-paradigm object-oriented languages. C++ is the example of multi-paradigm = il object-oriented language. & (ii) Hybrid Languages: Languages that support some (not all) of the object-oriented concepts are called hybrid languages. Java, Python and C# are examples of hybrid object-oriented languages. nyt Applications of OOP The application areas where OOP has been used to develop software are given below: 4, Simulations and Modelling (S&M): Simulation is the technique of representing the real-world eutities with the help of a computer program. Simula-67 and Smalltalk are two Object-Oriented (00) languages which are designed for making simulations, 2, Scripting: In recent years, OUP has also been used for developing HTML, XHTML and XML documents for the Internet, Python, Ruby and Java are the languages based on object-oriented principles which are used for scripting. 3. User Interface Design: This is the popular application of OOP in the area of designing Graphical User Interfaces (GUIs) such as Windows. C++ is mainly used for developing User Interfaces (Uls) 4. Object Databases: These days OOP concepts have also beeri introduced in database systems to develop a new DBMS named object databases. These databases store the data directly in the form of objects, however, these OOP databases are not as popular as the traditional RDBMS. aed 5. Developing Computer Games and Virtual Reality: OOP is also used for developing computer games such as Diablo and WarCraft IIL Those games offer virtual reality environments in which a mumber of objects interact with each other in complex ways to give the desired result, by * Some other areas of applications of OOP include Office Automation Systems (OASs), Real Time la ‘Systems (RTSs), Decision Support Systems (DSSs), Artificial Intelligence (Al) and Expert Systems (ESs), Neural Networks (NNs) and Parallel Programming (PPs) arid Computer Aided Design (CAD) Systems and so on. AS TT 410 Principles of Object Oriented Programming ‘Object Oriented Programming Using C+ trup at AT&'s Bell Labs in the early we Cr is an extension of C language, developed by Bjarne Strous Soao's, C++ is a general purpose programming language ‘which has been derived from C ‘programming language. + Ce+ could be considered a superset of C language with extensions and improvements with object crt nted features inckided in i. C++ runs on a variety of platforms, such as Windows, Mac 0S, UNIX, LINUX etc. «C++ is popular languages because of following reasons: 4. Ces is ideally suited for development of reusable software. 2, CH is highly flexible ianguage with versatility. Evolution of C++ ocr is an Object Oriented Programming (OOP) language developed by Bjarne Stroustrup. He is @ cre Or SIMULA 67 and C, warted to combine the features of both the Iangucihs and he developed 2 powerful language that supports abject oriented programming with features of C. The outcome | ‘was C++ as shown in Fig. 1.12. i 1s Tudlone features were derived from SIMULA 67 aid ALGO! 68, B. Stroustrup called the new language > “Curith Classes’. However, in 1988, the name was changed to C++ } +. Fig..42 evolution of C++. ‘The thought of C++ came from the ‘ jnerement operator ++. Rick Mascitti coined the term C++ in 1983, Therefore, C++ is an extension of ‘C’ and a superset of ‘C’. All the ; concepts of Care applicable to C++ also. } «For developing complicated applications, + object oriented language such as C++ is the H ‘most conventent and easy. canines are Features of C++ ocr language provides a lot of features that are given in Fig. 243, «Various features of C+ in Fig, 1.23 are explained below: simple; C++ isa simple language because it provides structured programming approach, rich set of library functions, data types etc. Stachine Independent or Portable: C++ programs can be executed in different computer ‘machines with little bit or no change. cng ESOT rlented Programing Using Crs an ] 4, Structured Programming Language: C++ is a © modify. Principles of Object Orlented Programming Mid-level Programming Language: C++ is regarded as a middle-level language, as it comprises 2 ~ combination of both high-level and low-level language features. structured programming language in the sense that we can break the program into parts using functions, So, it is easy to understand and 5: Rich Library: C++ provides alot of in-built functions that makes the program development fast, 6. Memory Management: C++ supports the feature of dynamic memory allocation. In C++ language, we can free the allocated memory at any time by calling the free() function, 7. Speed: The compilation and execution time of C++ language is fast. 8. Point +++ provides the feature of pointers. We can directly interact with the memory by using ‘the pointers. We can use pointers for memory, structures, functions, array etc. every function. Recursion: In C++, we can call the function within the function. It provides code reusability for 10, Extensible: C++ language is extensible because it can easily adopt new features. 11. Object Oriented: C++ is an object oriented programming language. OOPs makes development and maintenance easier. 42, Compiler Based: C++ is a compiler based programming language, it means without compilation " ho C++ program can be executed. First we need to compile the program using compiler and then ‘we can execute the program, Cvs C++ 1. | Clanguage was developed by Dennis Ritchie i 1972 at American Telegraph & Tele- communication (ATST) Bell Laboratories in Murzay hills, New Jersey, USA. C++ language was developed by Bjarne Stroustrup in early 1980's at American Telegraph & Telecommunication (AT&T) Bell Laboratories in Murray hills, New Jersey USA. 2, | Clanguage is a top-down structured program C++ is bottom-up object oriented prog- ming language. rammming language. 3. | C language programs are saved with .C file|C++ programs are saved with cpp file extension. extension. 4. | When compared to C++, Cisa subset of C++. (C++ is a superset of C. C++ can run most of C code while C cannot run C++ code. 5, | In C language, scanf() and printf are used as V/O functions. The header file required to | | include for this purpose is, "stdio.h". |tm C++ language, cout ard cin are used as Input/Output (1/0) facility. The header file required to include for this purpose is [“iostream.h*, 6. /C language requires format specifier for printing and scanning variables. [ces language does not require format specifier for printing and scanning variables, 7._| Cisa function-driven language. C++ is object-driven language. 8. | does not support OOPs concepts such as| C++ supports OOP concepts such as, class, class, object, inheritance, polymorphism, data | object, data hiding, polymorphism, hiding, etc. inheritance, abstraction, etc 9. | Clanguage isa middle level language. C++ is a higher level language, 10. |C does not support function and operator |C++ supports function and operator overloading. overloading. dject Oriented Programming Using C+4, a2 Principles of Object Oriented Programming Bg, Structure of C++ Program A computer program is a sequence of instructions or statements that tells the computer what to do. These statements/instructions form the structure ofa C++ program. + A.C# program is a text file containing a sequence of C++ commands (instructions) put together according to .he laws of C++ grammar or syntax rules. Finclude «Ce text file is known as the source saciaes file. A C++ source file carries the fle { extension .cpp. A typical C++ program ‘ ‘would contain following four sections: [Jf que a Fncont() 1. Includefile, - | { 2. Class declaration, 3, Member function definition, and 4, Main function. © Fig. 114 shows structure of a C++ program. unetion2() rmain() Fig. 1.24: Structure of C++ Program © C++ program is a collection of functions and list of library files(s) included for adding the contents to the C++ program. © Consider the following Hello World! program which shows basic structure of C++ program. include using namespace std; Ant main() { cout'<< "Hello World!" << endl; return @3 + output: Hello World! ‘© Line 4 #includeciostream is a preprocessor directive and it start from a # (hash) sign. This directive tells the preprocessor to include the “iostream" header file to support input/oxtput operations. All C++ programs begin with a "#include" directive that includes the specified header file contents into the main program. Old versions of C+ use a header file called as iostream.h. In this program, we are telling the compiler that we would like to use the fostream brary. The iostream library contains code that tells the compiler what cout and endl do, * Line 2 using nanespace std; tells the compiler to use the std (standard) namespace. In this program std is the namespace where ANS! C++ standard class libraries are defined. Namespace is a new concept introduced by the ANSI C++ standards committee. ‘This defines a scope for the identitiers ‘that are used in a program. For using the identifiers defined in the namespace scope we must include the using directive like Line 2. The names cout and endl, which is used in this program, ‘elong to the std namespace. + Line3 int main() declares the main() function which is the point from where all C++ program begin their execution. Every program must have a mainQ function, Line 4 contain the opening curly brace ({) which marks the beginning of the function or tody of the program. Line 7 contain the closing curly brace (}) which marks the end of function body cr program ody. Everything between the opening curly brace on Line 4 and the closing curly brace cn Line 7 is considered part of the main( function. soyvayye Object Oriented Programming Using C++ sas Principles of Object Oranted Programming [RP tercet cute eeu an eae canner cae an ee eae (or console output). The symbol << is called the stream insertion operator (put-to operator), which is ‘used to put the string "Hello World!" to the console. "endl" denotes the end-of-line or newline, which 1s put to the console to bring the cursor to the beginning of the next line, C++ also uses extraction operator >> (get-from operator) to read data form a standard input device, Line 6 return @; called a return statement. When an executable program finishes running, it sends a value to the operating system that indicates whether it was run successfully or not. The return value of main()is used for this purpose. This particular return statement returns the value of 0 to the operating system, which means “everything went okay!’ Comments in C++: * Comments are parts of the source code disregarded by the compiler. They simply do nothing, A comment is a sequence of characters, which improve the readability of a program. + Comments help to identify program purpose and explain complex routines. C++ supports two ways to insert comments: 1. Line Comment (//): A comment with // is called single line comment, 2, Block Comment (/* */}: A comment started with /* and ended with */ is called multiple line ‘comment or block comment. * The line comment, discards everything from where the pair of slash signs (//) is found up to the end of that same line, * The block comment, discards everything between the /* characters and the first appearance of the*/ characters, with the possibility of including more than one line. Program 1.1: Program for comments. 7* program with types of comments in C++ */ include usiig namespace std; ar Sn one int main() t cout << "Hello CH!" << endl; [prints Hello c++! cout << "Welcome to C++!" << endl; //Prints Welcome to C+! e return @5 1 + 2 output: © | Hello cei 8 | __Welcone to cH! ay a | : The characters are the most basic building blocks of the C++ language, A character set can be ; defined as, ‘a set of characters that either individually or in combination, represents some 7 information", i * The C++ program is made up of sequence of characters and consists of upper and lower case letters, digits, special characters and white spaces. The letters and digits together constitute the alphanumericset, * The class of characters, which are not printed, but instead, cause some action are commonly referred to as the control characters or white spaces, They are represented by a backslash (\) followed by ‘@uother character. a | ‘object Oriented Programming Using Crt 136 Principles of bjent Oriented Programming "sees character set consists of the following characters: { (Uppercase Letters) (Lowercase Letters) i Digits. { 0, 1, nm 9 Digits) & Ampersand symbol | Vertical bar 1 [: caret 7 Rightslash * Asterisk \ Backslash i / — Minus sign = Tilde symbol | ! + Plassign _ Underscore <_ Opening pointed bracket § Dollarsign | special | > Closing pointed bracket % Percent symbol j ‘Symbols ( Opening parenthesis . Dot 3 | Ae ) Closing parenthesis Comma = [Opening square bracket ;Semicolon : ] . Closing équare bracket + Colon i {. Opening brace 2 Question mark i } Closing brace * single quote | # Number sign “Double quote i = Equal symbol 1 Exclamation symbol j | Backspace vy j Horizontaltab Vt | | Vertical tab w 4 = White | Carriagereturn = \r i spaces | Newline \n Form feed \t Alert character \a Tokens in C++ + Tokens are the basic building blocks of C++ fe | | | | | | | programming language which are constructed together torte Gee program. [oases] © A token is defined as, "the smallest unit of a |-iiicirstni] program’. «Fig. 115 shows tokens in C++ language | [sens Fig. 1.15: Tokens in Cr+ EWE] Keywords - + ‘Keywords are the predefined words that have special significance in any language. Keywords or reserved words, have a specific meaning to the compiler and cannot be used in the program for other ss sd stem mea Coblect Orionted Programming Using C+ 115. Principles of Object Oriented Programming «Every Keyword is ceserved for a specific purpose and hence, cannot be used as user-defined names (identifiers) All the keywords of C++ are listed in Table 1.1. ‘Table 1.4: Keywords in C++ bool break auto asm catch case const | const_cast_| char class default | continue double | dynanic_cast | delete do ‘enun else float | for explicit, extern goto Friend int Jong if inline nanespace | mutable private | protected | new operator | register | public short | signed reinterpret_cast_| return static | sizeof snitch | template | struct static cast _| throw ‘this ‘typeid | union ty ‘typedet using unsigned virtual | while void [volatile BY identifiers in c++ + In C++, the names give to objects, structures, functions, arrays, etc. to identify them are called identifiers. An identifier is an arbitrarily long sequence of characters and digits like Student_Name, EmpID010 etc + Rules governing the construction of valid identifiers are: 1. The first character of any identifier must be a letter or an underscore (_).. 2. C++ is a case-sensitive language, hence, ‘STUDENT’ and ‘studerit’ or ‘Student’ are treated as separate characters and are therefore, two different identifiers. 4, An identifier should not be a keyword, 4, The length of identifier below 32 characters. Examples of valid identifier inC++: amarEmpID, studentI01@, EmpSal etc. Variables in C++ + A named memory location use to store data and whose content may change during program execution is called as variable + Avariable in C++ is an identifier that refers to the data item stored at a particular memory location. ‘This data item can be accessed in the program simply by using the variable name. The value of a variable can be changed by assigning different values to it at various places in a program, + The rules for defining variable names are listed below: 1. The name of a variable should be a unique and a valid C++ identifier. ‘Variables name can be aé short as a single letter and first 32 characters can be considered. Do not use keywords as variable names. Variable names must begin with a letter of the alphabet or an underscore Q. No blank space is allowed in a variable name. Declaration of Variables * The variable must be declared before they are used in the program. Once variable declared, the compile: obtains the variable name and the compiler is notified about the data type of the variable being declared and helps in allocation of the memory. * Ct permits declaration of variables anywhere in the program. This makes the programmer more comfortable to declare the variables and need not go back to the beginning of the program. * The declaration of variable consists of data type and variable name. The syntax for declaration of » variable is: data_type variable_nane; (bjoctGrontod Programming Using Co 146 Principles of Object Oriented Programming For example: int a; int x5y5 float a,b; #. Variables in C++ can be declared in three different places namely, inside functions, in the definition ~of function parameters and outside of all the functions. ‘The variables which are declared within a fanction are called local variables and variables which are declare outside the function are called global variables. «Declaration of variables in C++ makes a program easier to understand because variables are declare whenever, they are needed (at the time of their use). ‘Program 1.2: Use of variables in C++ program. #include using nanespace std; 1 Variable declaration: extern int a, bj extern int extern flodt?; int main() t 2 // Variable definition: int 2, b5 int.¢; oat #5 // ketual initialization a = 20; b= 49; c= a+ by cout < ¢ << endl 5 @= 73.0/3.0; cout << # << endl ; return 05 + output: 7 60 P} Initialization of Variables «© When a variable in C++ is declared, it allocates sufficient memory for variables. However, it does not store any data in the variables. To store data in variables, the variables need to be initic lized at the time of declaration. «Initialization of variable can be done at the place where it is declared or anywhere in tae program before their use. Variables declared can be assigned or initialized using assignment operator (=). «© I€we want to initialize the variable to the specific value the following syntax is used: dats_type variable_nane = initiel_value; For example: int x = @; © Variables in C++ can either be initialized at the compile-time or at the run-time. Initializetion at the compile-time using a constant is known as static initialization, However, variables can also be initialized at the run-time using expressions known as dynamic initialization. ae at its Object Oriented Programming Using C+ a7 Principlos of Object Orionted Programming program 1.3: Program to demonstrate the static and dynamic initialization of variable. “Hnclude using nanespace std; int maiii() { int NI=9, Ni //static initialisation using constant int N3=NLN; //Oynanic initialisation using expression cout cen; return @5 } output: 4 «Constants in C+ refer to fixed values that do not change during the execution of a program. Consta.tts are also called asliteruls, + Fig. 146 shows types of constants in C+. Fig. 1.46: Constants in C++ * Various types of constants in Fig, 1.16 are explained below: 1. Numeric Constants: _ ‘+ These constants refer to the numbers consisting of a sequence of digits (with or without decimal point) that can be either positive or negative, However, by default, numeric constants are positive. + Numeric constants in C++ can be further classified as integer constants and floating-point constants which are explained in Table 1.2. of Numeric Integer constants refer to integer-valued numbers. 63 Decimal constant ‘They can be represented by three different number | 117 Decimal constant systems, namely decimal (base 10), octal (base 8) and | 91612 Octal constant hexadecimal numbers (base 16). The-octal constants | @x38A Hexadecimal constant are preceded by a 0 (zero) and hexadecimal constants | are preceded by a Ox or OX. 2, | Floating-point constants refer to the real numbers, | 20.23 that is, the numbers with a decimal point. Floating- | ~64.31 point constants are also written in the floating-point notation in Which the constant is divided into a mantissz and an exponent. 2. Non-numeric Constant * Character constant have either a single character or group of characters or character with backslash (used for special purpose. * Following are the types of character constants in C++: () Single Character Constant: A character constant is a character which is enclosed in single quotes * ’. A character constant is of size 1byte and can contain only 1 character, Example: ‘Amar’ ‘a? “b? (8 '#! Principles of Object Orionted Prograniming ‘Object Oriented Programming Using C++ ‘A string constant is a collection of characters enclosed in double (ii) String Constant quotations” ”. Example: "Wirali Prakeshan®, ‘Anan and akbar”. « cawalso support symbolic constant. A symbolic constant is referred to as a name thet substitutes for constant that may bea numeric constant, a character ‘constant or a string constant. «We ean assign a constant value to a variable which cannot change at run-time using ‘const’ keyword known as symbolic constant. The syntax is given below: const datatype variable = value; For example: const double PI = 3.14; « Wecan also define symbolic constant using ‘#define’ preprocessor directive. + Thesyntaxis: #deFine nane value Forexample: define PI 3.14 Data Types : © Adata type determines the type and the operations that can be performed on the data. A data type is defined as, “the set/collection of values and the set of operations that operate on those values”, ‘» ‘Inshort, the word data type is analyzed as follows: Data Type = Permitted Data Values + Operations «= ‘The various data types provided by C++ are built-in data types, derived data types and user-defined data types as shown in Fig. 1.7. | ' i Fig. 147; Hierarchy of C++ Data Types 4, Built-in Data Type: Built-in data types are atomic data type which is not composed of other data types. C++ compilers support all the built-in (also known es basic or fundamental) data types as shown in Fig. 1.17 = Canbasie data types are integer, float, character and boolean. C++ uses two moze data types, bool andwehar.t. © The Table 1.3 shows the description of C++ basic data types. ‘Table 2.3: Built-in Data Types in C++ char ‘byte am torz7ordto2ss | unsigned char Abyte Oto 255 signed char byte = 12710127 int, Abytes = 2147483648 to 2147483647. : unsigned int. ‘bytes ‘9 t0 4294967295 _ le is epee object Oriented Programming Using C+ 139 Principle of Object Orionted Programming signed int ‘bytes 1147483648 to 2147485647 short int 2bytes = 32768 to 32767 unsigned short int Range (010 65,535 signed shert int Range = 32768 to 32767 Jong int bytes | -2,147,483,648 to 2,147,483,647 signed long int bytes same aslong int unsigned long int a bytes 0t04,294,967,295 | fcat bytes +$/-3.0 @ +/° 38 (-~7 digits) double bytes +/-L7 e +/=308 (-15 digits) Jong double Bbytes $/-17e +/-308 (~15 digits) wechar.t 2or 4 bytes iwide character + The bool data type can hold only boolean values, is, either true or false, where true represents and false represents 0. It requires only one bit of storage, however, itis stored as an integer in the memory. Thus, itis also considered as an integral data type. + The void data type is used for specifying an empty parameter list to a function and return type fot a function. When void is used to specify an empty parameter list, it indicates that function does not take any arguments, and when it is used as a return type for a function, it indicates that a function does not return any value, + The void is used for following two purposes: () ‘Ifthe function is not having any arguments, runction_Nane(void) (i) To specify the return type of function when function is not returning any value. void function_nane (void); 2, User-defined Data Types: * User has the facility in the programming language to create data types according to his/her own needs, The data types defined by user according to his/her needs/requirements known as user- defined data types. @) structure: © Asstructure is group of variables of different data types considered as a user-defined data type. To create a structure, use the ‘struct’ keyword, followed by a name of the structure, and torminated by a semi-colon () © Astructure can be created as follows strucy structure_name € /Mvariables of different deta types Z For example: struct student 4 char name(20); ong phone; h © By default members of the C++ structures are public. User can create a variable of structureas, structure_name variable_name; ‘Object Orlented Programming Using C++ 120 Principle of Object Orlented Programming (i) Class: ~ o InC++a class is a user-defined data type. A class acts as a template which defines the data and functions that are included in an object of the class. © Classes are declared using the keyword ‘class’. Once, the class has been declared, its object can beeasily created. For example: class student t private; char name[20]; public: void display() 1 cout |Tocheckifthe value of [Binary | a>20willreturn Oas one variable is greater the condition is false. 7 than the other variable, i 4, | GreaterthanorEqual | >= [Tocheckifthevalueof | Binary | a>=20 willreturn Oas to one variable is greater the condition is false. than or equal to the to other variable. 5. | Equalto == |Tocheckif the valueof 7 Binary | a==bwillreturn Oas ‘two variables is equal. the condition is false. 6. | Not equal to Tocheckifthevalueof — [Binary | aleb, itwillretun 1as | two variables is not equal. the condition is true. I | Object Oriented Programming Using C++ 124 Principles of Object Oriented Programming 3. Logical Operators: ‘+ Logical operators, in C++ combines the results of two or more than two expresions. The mode of connecting relationship in these expressions refers as.lgoic and the expressions are called logical expresions. The logical expression returns 1 if the result is true and its returns 0 if the result is false. *_ Following To return true if the conditicns are true, return O as both the conditions are not true 2. [OR | | Toreturn trueifatleastoneof | Binary | a<20|/b>6villreturn1 the conditions is true. as one of the conditions is true ct 3. [NOT 1 |Tonegate the value ofa Unary | !a<20willreturn 0 as relational expression. = the negated value. 4, Assignment Operators: + Assignment operators that are used to assign the operator on the left the value on the right. The basic assignment operator is the "=" operator. '* Compound/shorthand assigninent operators are used modify the current value stored in a variable. Some of the compound assignment operators are given below: cript A 2 A ee fee Bee i 2 ‘= | Simple assignment operator, assigns values, +b will assign value of a +b from right side operands to left side intoc. operand, z += | Add AND assignment operator, adds right | c+=alsequivalenttoc=>+a operand to the left operand and assign the resuit toleft operand. 3. “= [Subtract AND assignment operator, | ¢—=als equivalent toc=c-a subtracts right operand from the left operand and assign the result to left operand, 4 * ‘Multiply AND assignment _ operator, multiplies right operand with the left operand and assign the result to left ‘operand. 5 7= [Divide AND assignment operator, divides | ¢/=ais equivalenttoc=>=2is same asc=co>2 9. Bitwise AND assignment operator. c= 2is sameasc=c&2 70. Bitwise exclusive. OR and assignment | c’=2issameasc=c"2 oes operator. it Bitwise inclusive OR and assignment | c|=2issamease=cl2 operator. Object Oriented Programming Using C++ 13 Principles of Object Orlented Programming 5. Bitwise Operators: ‘+ Bitwise operations in C++ are zefer to testing, setting, or shifting the actual bits in a byte or word, which correspond to the char and int data types and variants. * Bitwise operators are used for manipulating the integers at bit level. The binary representation of the integer gets altered as per the type of binary operator applied. Following table Lists the various bitwise operators in C+: AND & | Toperform logical AND Binary | 0101 & 0011 = 0001, operation at bit level. 2. [oR | [To perform logical OR Binary | 0101/0011 = 0111 om operation at bit level. 3. [Excusiveor | * | To perform logical exclusive | Binary | 0101 001120110 ORoperation at bit level. 4, | Shifcteft <<_|Toshiftthebitstotheleft. | Unary | 00010111 <<1 = 00101110 s._| shift Right >>| Toshift thebitsto the right. | Unary_| 00010111 >> 1= 00001011 6. | Complement | ~ | Tonegateeachbitofthe | Unary | ~0001=1110 or Not binary number. : 6. Conditional Operator: © Conditional operator is also called as ternary operator. It operates on three operands which is why itis called ternary. Itis represented by (?:). © The syntaxis, condition expression? expression 1: expression 2; © The condition expression is evaluated first and if true then expression 1 is evaluated otherwise expression 2 is evaluated, For example: float a = 15; float bc; (2 < 20)? b = 50: ¢ = 100; © All chese above operators are valid in C++, C++ have some other operators given below: endl Line feed operator setw Field width operator new — Memory allocation operator delete Memory release operator Scope resolution operator Pointer-to-member declaration Pointer-to-member operator + Pointer-to-member operator © _C++also provides new meaning of some bullt-in-operators. This is operator overloading, Precedence of Operators: * The precedence order of operators is the order in which operators aré executed in an expression. ‘The operator precedence in C++ determines the order of execution of operators by the compiler. An operator with a high precedence is used before an operator with a low precedence. Forexample:m=x+y"z * In the above example, the multiplication operator (") has a higher precedence than the addition (+) and the assignment operators (=). So, the value of the variable by is multiplied by the value of variable z and then the resultant value is added to the variable x (because the addition operator has a higher precedence than the assignment operator). Next, the resultant value of the expression (x+y"2) is assigned to the variable m. a ced Object Oriented Programming Using C+ 33s Principles of Object Oriented Programming Operator Associativity: ‘+, When two or more operators have the same precedence in an expression, the order in which the operation is performed is defined as the associativity of an operator. The following are the two types \.. of associativity in CH: i “Ns0°8" i Unithe Left to Right Associativity all the operations are performed from the left to the right, For example: m=%+y+z In the above example, the addition operator has the left to the right associativity, So, the value of variable x is added to the value of variable y. Next, the resultant value is added to the value of the variable 2. 2, Inthe Right to Left associativity all the operations are pe: formed from the right to the left. For example: a+ =b In the above example, the compound assignment operator has the left to the tight associativity. So, the value of variable a is added to the value of variable b. Next, the resultant value is assigned back to variable a, Right toleft Multiplicative Left torright ‘Additive Lefttoright — Shift Left toright Relational Lefttoright | Equality Lefttoright Bitwise AND Left toright Bitwise XOR Left toright Bitwise OR Left toright Logical AND Left toright Logical OR Left toright Conditional Right toleft ‘Assignment ia toads cee Ba Right to left Comma 5 Left toright GB) Expressions * An expression is any statement which is composed of one or more operands and returns a value, An expression is a combination of operators, constants and variables arranged as per the rules of the i language. 4 * The expression may be simple to complex. For example, z = x + y; is an expression which adds two variables xandy. i * An expression may also include function calls which return values, An expression may consist of one or more operands, and zero or more operators to prodice a value, * Depending upon the type of operands involved in an expression or the result obtained after evaluating expression, there are different categories of an expression. These categories of an expression are below: 1. The expressions that comprise only constant values are called constant expressions. Some examples of constant expressions are 40, ’b' and 3/5+20. 2, The expressions that produce an integer value as output after performing all types of conversions are called integral expressions. For example, a, 5°a-b and 20 +int (.0) are integral expressions, 3. The expressions that produce floating-point value as output after performing all types of conversions are called float expressions. For example, 2.25, a-d and 2+ float (3) are float expressions. Here, a and b are variables of type float. Object Orlonted Programming Using C++ mer Principles of Object Oriented Programming 4, The expressions that produce a bool typé value, i.e, either true or false are called relational or Boolean expressions. For example, a + b<100 and a>=b + care relational expressions. 5. The expressions that produce a bool type value after combining two or more relational expressions are called logical expressions. For example, a==5 &80==5 is logical expression. 6, ‘The expressions which manipulate data at bit level are called bitwise expressions, For example, isa >> 2and be<4 are bitwise expressions. 7. The expressions that give address values as output are called Pointer expressions, Fox example, &ocis a pointer expression. 8, An expression can be categorized further depending upon the way the valves are assigned to the variables, known as special assignment expressions. 9. Chained assignment is an assignment expression in which the same value is assigned to more than one variable, using a single statement. For example, consider these statements. ~ x = (y=20)} 07 xeyn205 In above statements, value 20 is assigned to variable y and then to variable x, Note that variables cannot be inicialized at the time of declaration using chained assignment, For example, consider these statements. int x=y=30; // illegal Ant x=30, int y=3@; //valid 10. Embedded assignment is an assignment expression, which is enclosed within another assignment expression. For example, consider following statement, x=20+(y=30); — //equivalent to y=30; x=20+30; In above statement, the value 30 is assigned to variable y and then the result of (20+30) that is, 50 is assigned to variable x. Note that the expression (y=30) is an embedded assigument. Compound assignment is an assignment expression, which uses a compound assignment operator that isa combination of the assigninent operator with a binary arithmetic operator. For example, consider following statement, 5 x +9203 /Vequivalent to x=xs20; In above statement, the operator += is a compound assignment operator, also known as short- hand assignment operator. ‘Typecasting * ‘Typecasting means the conversion of one data type to ancther data type. For example, a float value can be converted into an integer value. + There are two types of type conversions in C++ namely automatic conversion (or implicit conversion) and type casting (or explicit conversion). 4. Implicit Typecasting: * In implicit type casting, the conversion is done automatically by the compiler. In this type of conversion, a sinaller data type is converted into a larger data type. * Most binary operators require thelr operands to be of the same type. If mixed expression is used then compiler will convert one type into another type using following hierarchy of data types. * Ifa value in a smaller variable (at lower level in hierarchy) is assigned to a larger variable with no 1, loss of data then it is called as widening or Ty promotion. Widening conversions are always safe pe they don't result in data loss. Fig, 1.49: Implicit Type Conversion of Hierarchy ‘Object Orlented Programming Using C++ 1.28 Principles of Object Orlented Programming ‘© When compiler tries to convert higher level data type into lower level type, itis known as narrowing or coercion. Narrowing may results in a possible data loss. ‘+ For example, in below code assignment of integer to double is safe while double to integer results in loss of fractional part. double d = 2.8; Ant 43 ded; ind; © If the conversion’ is a promotion or widening, the compiler does not issue a warning. If the ‘conversion is a narrowing, the compiler issues a warning about possible data loss. 2. Explicit Conversion or Typecasting: ‘* It refers to the type conversion that is performed explicitly using type cast operator. In C++, typecasting can be performed by using two different forms which are given below: data_type(expression) //expression in parentheses OR (data_type)expression //data type in parentheses where, data_type is a data type (also known as cast operator) to which the expression is to be converted. ‘© Typecasting is a request by the programmer to do an explicit type conversion. For example: int i = (int) 20.23 ‘In the above example, the value (20.23) is converted into an integer value (20) and aft r that the resultant value (20) is assigned to the variable i. Here, int is used as a (type) operator to convert the float value into an integer value. © The following Program 1.4 will convert a float type value into double and then the same value into an int data type. {twill also display the resultant values on the screen. ‘Program 1.4: Program to convert a float value to a double value and also a float value to an integer type #include using namespace std; int main() { int 4; float x=10.23; double ys yox //implicit conversion or typecasting coutc<"Value of y is: " using ranespace- std; .. int main() \ € J/ statement(s) will execute if the boolean expression is true int a = 18; 71 check the boolean condition AFC a < 20) 11 Af condition is true then print the following cout << "a is smaller than 28” << endl; z cout << "value of ais : " <¢ a << endl; return @5 } Output: a ds smaller than 20 value of a is : 18 —— a ia! + Object Oriented Programming Using C++ 4130 Principle of Object Orlonted Programming Program 1.6: Program to print positive number entered by the user. include using namespace std; int main() { ‘int numbers cout << "Enter, an integer: ", cin >> number; * JJ checks if the number is positive if ( number > 0) { ‘cout << "You entered a positive integer: " << number << endl; } cout << "This statement is always executed."; return @5 } ‘Output 1: Enter an integer: 5 ‘You entered a positive number: 5 ‘This statement is always executed. Output 2: Enter 2 number: -5 ‘This statement 15 always executed, ‘else Statement: In C+4, if...else statement is a two way branching statement. If the Boolean expression evaluates to true, then the if block of code will be executed, otherwise else block of code will be executed, ‘Syntax: 4F(boolean_expression) { // statenent(s) will execute if the boolean expression is true } else € // statement(s) will execute if the boolean expression is false } Program 1.7: Program to check whether number is Even or Odd using if..else statement. #include using hanespace std; int main() { int ni; cout << "Enter an integer: if (82 == 0) cout << n <<" is even else cout << n cc * 4s odd."5 return 0; ‘ 3 output: Enter an integer: 55 55 is odd. Object Oriented Programming Using C++ 131 Principles of Objaet Oriented Programming Program 1.8: Program to check Leap year or not, #includeciostream> using namespace std; int main() C int years coutc<"Enter the year : cinp>year; coute<"\n"; 4Af( ((year&4==@) && (yearkie@!=8)) || ( year%aee==0) ) coutccyearc<" is a leap year\n"; else coutccyearc<" is not 2 leap year\n"; return @; y Output: Enter the year : 2618 2018 is not 2 leap year ‘Nested if Statement: ‘* When one if statement contains another if statement then the statement is called as nested if statement, Syntax: Af (expression 1) { if (expression 2) i [/statenent blocks y > Program 1.9: Program to find largest of three numbers. #includeciostrean> using nanespace std; int main() { int x y,2,bi8; coutc<"\nEnten the three numbers : einooxosyoz5 bigex; //assuming ‘x’ as the largest nunber sf (yrbtg) bigeys if (z>big) bi coute<"\nlargest number ise return 95 } Output: Enter the three numbers : 18 30 26 Largest _nunber is= 30 __ Object Oriented Programming Using C+ 132 Principles of Object Oriented Programming Nested if...else Statement: © Anested if...else statement contains one of mcre if...else statements. When one if...else statement contains another if statement then the statement is called as nested if..else statement, Syntax: if (condition) { statement; - ~4# (condition2); statenent2; else statement3; t else + { statement4; if (condition3) #include using namespace std; int main() t int age; cout <: "Enter your Age::"5 cin >> age; Af (age >=10 8& agec=50) { rf Af (age >=10 a8 age <= 18) { cout << "You are a Teenage" << endl; statenent5; = else statenents; : + Program 1.10: Program for nested if statement. } else t cout << "You not a Teenager” << endl; ? y else { 1 cout << "You are more than S@ years" << endl; } return 0; i Output: Enter your Age::30 You not a Teenager Object Orlonted Programming Using Cs-+ 4133 Principles of Object Orlonted Programming 3. switch Statement: : © switch statement allows a variable to be tested for equality against a list of values. Each value is celled a case, and the variable being switched on is checked for each case. syntax: switch expression) t : case constant-expression: statement(s); break; //optional case constant-exoréssion: statement(s); break; //optional // One can have any number of case statenents default: //optional statement(s); } Program 1.11: Program for switch statement: #includeciostream> using namespace std; int main() t int a; cout<<"Enter the no : "3 cind>a; suitch(a) { case 1: coutc<" sunday\n"; break; case 2 coute<"nonday\n" break; case 3: cout<<"tuesday\n"; break; case 4: cout c<"wednesday\n" ; break; case S: cout<<"thursday\n" break; case 6: coute: break; case cout<<"saturday\n™ break; defoult: coutc<"wreng option"; } return @; friday\n"; } output: Enter the no: 4 wednesday Object Oriented Programming Using Cr+ 138 Program 1,12; Program for print grade using switch statement, #include using namespace std; int main © t /1 local variable declaration: ctiar grade = ‘0 sviitch(grade) t case ‘At: cout << ‘Excellent!" << endl; break; case "8" case ‘Cc! cout << "Well done" << endl; break; case 'D' : cout << "You passed” << endl; break: case 'F* cout << "Better try again" << endl; break: default cout << “Invalid grade" << endl; r cout << “Your grade is " << grade << endl; return 0; 4 Output; You passed Your grade is D Principles of Object Orientad Programming ‘Nested switch Statement: ‘© It is possible to have a switch as part of the statement sequence of an cuter switch. Even if the case constants of the inner and outer switch contain common values, no conflicts will arise, © The syntax for a nested switch statement is as follows: switeh(cht) { case "At: cout << "This A is part of outer switch"; switeh(ch2) { case "A": cout << "This A is part of inner switch"; break; case "BYE // 2. ? breaks case ‘BY: // wes (Object Oriented Progremming Using C++ 1.35 Principles of Object Oriented Programming Program 1.13: Program for nested switch statement, #inelude using namespace std; int main () { JI loca: varsable declaration: int x = 100; Ant y = 2005 switeh(x) { case 100: cout << "This is part of outer switch" << endl; switch(y) { case 200: cout <<¢ “This is part of inner switch” << endl; | } } cout << "Exact value of a i cout << “Exact value of b is: return 0; "ec x €¢ endl; ce y << endl ? Output: This is part of outer ‘switch This is part of inner switch Exact value of x is: 108 Exact value of y is: 208 Loops © The statements that cause a set of statements to be executed repeatedly either for a specific number of times or until some condition is satisfied are known as loop. That is, as long as the condition evaluates to True, the set of statements is executed, * The loop defined as, a block of statements which are repeatedly executed for certain number of times, The various iteration statements used in C++ are for loop, while loop and do-while loop. |. while Loop: ‘+ Awhile loop statement repeatedly executes a target statement as long as a given condition is true. Syntax: while (condicion) { statenent(s); + e + Here, statement(s) may be a single statement or a block of statements. The condition may be any expression, and true is any non-zero value. The loop iterates while the condition is true, * When the condition becomes false, program contiol passes to the line immediately followring the loop. Program 1.14: Program to compute factorial of number. include using namespace std; int main() { int number, i = 4, factorial = 1; cout << “Enter a positive integer: "; cin >> number; ‘Object Orlented Programming Using Cr+ 136 Principles of Object Orientod Programming while (4 <= nunber) factorial * 4; //factorial » factorial * i; + coutc<*Factorial of "<< number <<" = “cc factorial; return 0; } Output: 2: Enter a positive integer: 5 Factorial of 5 = 128 for Loop: {A for loop is a repetition control structure that allows us to efficiently write a loop that needs to executea specific number of times. Syntax: for (init; condition; increment/decrenent) statement(s); } Here, is the flow of control in a for loop: © The init step is executed first, and only once. This step allows us to declare and initialize any loop control variables. We are not vequired to put a statement here, as long as a semicolon appears. © Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the ody of the loop does not execut and flow of control jumps to the next statement just efter the for loop. © After the body of the for loop executes, the flow of control jumps back up to the aicrement statement. This statement can be left blank, as long as a semicolon appears after the condition. © The condition is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then increment step, and then again condition). After the condition becomes false, the for loop terminates. Program 1.15: Program to display multiplication table up to 10. #include using namespace std; Ant main() { int nj cout << "Enter a positive integer: "; cin >> n5 for (int i #1; 4 <= 10; +41) { cout ence KECK M Ecc HA KK endl; > return 0; } ‘Output: Enter a positive integer: 3 B13 3226 38359 a%aei2 35245 356-38 Be 7221 388-24 369827 3 * 10 = 30 object Oriented Programming Using C++ 137 Principles of Object Oriented Programming Program 1.16; Program for Fibonacci Series up to n number of terms. #include using namespace std; int main() { int n, ti = @, t2 = 1) nextTerm = @; cout << “Enter the number of terns: cin >> nj 4 cout << "Fibonacci Series: "; for (int 1 = 4; 4 using namespace std; int ain() ‘ int sum=2,n5 cout <<"\nHow many natural numbers you want to print with their sum:\n"; cin on cout<<"\n"<<*Natural numbers are:\n"; for(int is1:i¢ensi4+) { coutecice? sumed; } coute<"\i\nsum : "< using namespace std; Ant main() { Ant ni, n2, max; cout << "Enter two numbers: cin >> nd >> 25 // maximum value between ni and n2 is stored in max max = (nd > m2) ? nd: n25 do { . Af (max % nl a= @ && max % n2 == 0) { cout << "LOM =" <« max; break; } else +max; } while (true); return @; } Enter two nunbers: 10 15 Lem = 36 ‘A loop can be nested inside of another loop called as nesting (nested) loop. ‘The syntax for a nested for loop statement in C++ is as follows: for (init; condition; increment) { for (imix; condition; increnent) { statenent(s); } statement(s); // you can put more statements. Object Oriented Programming Using C++ 139 ‘+ The syntax for a nested while loop statement in C++ is as follows: while(condition) { while(condition) { statenent(s); } statement(s)3 // you can put nore statements. + * The syntax for a nested do,..while loop statement in C++ is as follows: do { statement(s); // you can put more statenents. Z do { statenent(s); } while( condition ); } while( condition ); + The following program uses a nested for loop to find the prime numbers from 2 to 20, #incluée costream> using nanespace std; int main () { int 4, 35 for(d = 25 420; 444) ¢ for(j = 23 4 <= (4/3)3 344) 4#(1(483)) break; // Af factor found, not prine 4#(4 > (4/3) cout << i ce" 4s prime\n"; t return @; ? Output: 2 is prime 3 4s prime 5 4s prime 7 4s prime 11 is prine 13 4s prime 17 4s prime 19 is prime ‘Loop Control Statements: i * loop control statements change execution from its normal sequence. When execution leaves a scope, altautomatic objects that were created in that scope are destroyed. ‘+ Jump statements are used to alter (mod!fy) the flow of control unconditionally ie,, jump statements transfer the program control within a function unconditionally. + The jump statements defined in C++ are break, continue, goto and return. In addition to these jump statements, a standard library function exit() is used to jump out of an entire program, 1. break Statement: + When the break statement is encountered inside a loop, the loop is immediately terminated and program control resumes at the next statement following the loop. + _Itcan be used to terminate a case in the switch statement. ‘Syntax: break; ‘Object Oriented Programming Using Cr+ so Principles of Object Oriented Programming Program 1.19: Program to demonstrate working of break statement, include ' using nanespace std; int main() { float nunber, sum = 0.0; // test expression is always true while (true) { { cout << “Enter a number: "3 cin >> number; i if (number I= 0.0) { | sum += number; } alse // terminates the loop if nunber equals 0.0 | breaks j + \ ] } cout << "Sun =" << sums { return 2; ; } i Output: | Enter 2 nunbe 5 4 e Sun = 9 2. continue Statement: ‘*| The continue statement works somewhot like the break statement. Instead of forcing termination, ‘however, continue forces the next iteration of the loop to take place, skipping any code in between. © For the for loop, continue causes the conditional test and increment portions of the loop to execute. For the while and do...while loops, program control passes to the conditional tests. Syntax continu Progam 1.20; Program to add the factors ofa number, #includesiostream> using namespace stds int main() { Ant an@,b, sum=0; coute<"Enter a number:"; cind>b; while (2) 4 yay 4#(a>b) breaks i#(b¥al=0) continues sun=sumta; ; } coutc<"\nSum of factors:"< using namespace std; int main() { float num, average, sum = 0.0; int 4, m5 cout << "Maximum nunber of inputs: "3 cin >> a5 for(i « 15 4 <= nj 444) { cout << “Enter n” ced ce": ty cin >> num; ‘ if(oun < 0.0) { J Control of the progran move to jump: goto jump; ) sum += nun; > jump: average = sum / (4 - 1)3 cout << "\naverage = " << average; return 0; 3 output: Maximum nunber of inputs: 18 Enter nt: 2.3 Enter n2: 5.6 Enter n3: -5.6 Average = 3.95 4. exit) Function: ‘* We can oreak out of a program by using the standard library function exit). This function causes immediate termination of the entire program, no matter where it appears in the program listing, forcing a return to the operating system. ‘The general form/syntax of the exit() function is, void exit(int return_code); * The value of return_code is returned to the calling process, which is usually the operating system, Zero is generally used as a return code to indicate normal program termination. Other arguments are used to indicate some sort of error. The exit() function requires inclusion of the header file , Object Orlented Progéarming Using C++ 14. Principles of Object Oriented Programming | 7% program 1.24 Prograin to demonstrate thé use ofexit( function, ¥ . | #includeciostrean> seeage je fineludecestdlit>.//far exit()function i * "using namespace std; int-main() { Ant x5 coutce"Enter the value for whille(cin>>x) if (x0) t cout <<"This program is going to terminate exit (0)5 } coutce"Enter another value for a: "s i return 03 e } c Output: res entier the value for x: 5 Enter another value for a: -5 Ff pu_This progran is going to terminate! ‘Program 1.22; Program to check whether given number is perfect number or not. 4 Finclude using nanespace std; int main() t Ant. nun, sum=0, 45 cout<<"ENTER A NUMBER: 7: ccim>>num; For(ix154¢=(nun/2) 314+) { if(num % 1==0) i sum = sum + 45 } ? cout using nanespace stds int main() { Ant orighun, num, rem, sun = @, digits cout > ondgNuns num = orighuns while(num I= 3) { digit = num % 10; sun += digit * digit * digit: | num /= 10; } if(sun == ordgNun) cout << ordgNum <<" is an Armstrong number else ccut << origNum <<" is not an Armstrong nunber,"; return 95 3 } Output: Enter @ positive integer: 153, 4153 {s an Armstrong number. Program 1.24: Program to check whether a character is vowel or consonant. ‘Winelude a using namespace std; int main() ‘i fe char c3 int AsLowercaseVonel, isUppercaseVovel; cout << "Enter an alphabet: “3 cir >> ¢; J/ evaluates to 1 (true) if ¢ is a lowercase vowel Aslowercasevowel = (¢ == 'a” || c == 'e" || c== ‘i |] eae ‘0! |] c= // evaluates to 1 (true) if ¢ is an uppercase vowel isUppercaseVowel = (c == ‘A’ || ¢ "E’ |] cme tI |] cm 0" [fc ae tU')5 ‘// evaluates to 1 (true) if either isLowercaseVowel or isUppercaseVowel is true 4f (AsLowercaseVowel || isUppercaseVowel) cout << ¢ << " 4s @ vowel."; : else cout << ¢ << * As @ consonant. return 0; } output: Enter an alphabet: 1 I is a vowel. — ‘Object Orlanted Programming Using C++ 144 Priniples of Object Oriented Programming ‘Program 1.25: Program to check whether a number is palindrome or not. ‘include using namespace std; _ Aint main() i Ant n, num, digit, rev = 6) cout << "Enter a positive number: "5 ‘edn >> nun n= s.am5 do digit = num % 105 rev = (rev * 10) + digit ‘num = num / 103 } while (num I= 0); cout << * The reverse of the number i Af (n == rev) ‘cout <<" The number is a palindrome"; else ‘cout << "The number 4s not a palindrome"; return @; ce rev << endl; + } Output4: Enter a positive number: 12321 The reverse of the nusber is: 12321 The number 4s a palindrone output: Enter a positive number: 12331 The reverse of the nunber is: 13321 The nunber.1s'not_a palindrone ‘Program 1.26: Program to display factors of a number. ‘#include using namespace std; Ant main() 1 int ny 43 cout << "Enter a positive integer: "j cin >> n5 cout << “Factors of "<< n << "are: “ << endl; for(i = 25 4 <= nj +44) iF(n Xi == 0) cout << 4 <<-endl; t return 0; } output: Enter @ positive integer: 24 Factors of 24 are: 1 Object Orientod Programming Using C++ 14s. Principles of Object Oriented Programming Program 1.27: Program to check whether a number is prime or not. #include using namespace std; Aint main() t int ny 45 bool isPrime = true; cout << “Enter a positive integer: "; cin > 5 for(i = 25 £ cen / 25 444) { if(n % i n= @) { isPrime = false; * break: ‘ + if (isPrime) cout << “This is a prime number"; else cout << “This 4s not @ prime nunber return 0; + output: Enter a positive integer: 19 | This js a prime number ZS Program 1.28: Program to find largest number among three numbers. include using nanespace std; int main() t € float ni, n2, 3; cout << "Enter three numbers: ‘ein >> nt >> m2 >> 35 AF (nd >= 02) && (nd >= n3)) cout << “Largest number: * cc ni; else if ((n2 >= nt) && (n2 >= n3)) cout << “Largest number: " << 12; else cout << "Largest number: " << a return @; ? Output: Enter three numbers: 55 66 44 Largest nunber: 66 ' ‘Object Ortented Programming Using S++ 148 Principles of Object Oriente Progra.aming ‘Program 1.29: Program to print half pyramid using". include | using namespace std; ] int main() | ‘ Ant rows3 cout << "Enter number of rows: "3 cin >> rows; for(int i = 1; i <= rows; ++i) for(int j= 1; J <= 4; +49) | : { cout << "* } 7 cout << "\n"5 | - oxi | { + return 05 i Enter number of rows: 5 n Program 1.30: Program to print half pyramid a using numbers: 3 Ba 12345 #include | using namespace std; int main() { Ant rows; cout > rows; for(int {= 1; 4 <= rows; +44) { for(int j= t ppc ds 4g) cout << 4 << + . i cout << "\n"5 + return @; joctOrtented Programming Using C++ 147 Principles ct Objoct Oriented Programming 7 output: 4 Enter nunber of rows: 5 1 1 1 1 1 Program 1.31: Program to print half pyramid using alphabets. A Be ccc Dopp EEEEE #include using namespace std; Ant main() { char inpet, alphabet = 'A'; cout << "Enter the uppercase character you want to print in the last row: "j cin >> inputs | for(int 1 = 15 4 <= (input-"a's1); +44) { for(int j= 4; J ce 4; +44) { cout << alphabet <<" "5 > +ealphabet; cout << endl; > return 0; y Output: Enter, the uppercase character you want to print in the last row: A Be ccc Dood EEEEE Progeam 1.32: Program inverted half pyramid using *. #include using namespace std; 7 i Ant nain() { int rows; cout << “Enter number of rows: “} cin >> rows; | 4 j Object Ortented Programming Using Cee 148 for(int 4 = rows; 4 >= 13 --£) t for(int j= 45 j <= i; +49) t . cout <<" "5 } cout << endl; + return 93 ? Output: Enter number of rows: 5 Principles of Object Oriented Programming ‘Program 1.33: Inverted half pyramid using numbers. 12345 1234 123 12 - #include using namespace std; int main() { int rows; cout << “Enter number of rows: cin >> rows; for(int 1 = rows; 1 >= 45 { 1) for(int j= 1; J <= 4; +49) { cout << "* } cout << endi;. } return @5 t Output: Enter nunber of rows: 5 12345 1234 123 12 1 bje>t Oriented Programming Using C+ 100 Principles of Object Oriented Programming Program 1.4: Program to print full pyramid using *. include using namespace std; int main() t Ant space, rows; cout <<"Enter number of rows: cin >> rows for(int i= 1, k= 0; 4 <= rows; +44, k = @) { for(space = 15 space <= rows-i; +4space) C cout <<" "5 + while(k I= 2*4-1) { cout << “* hs i : cout << endl > return @5 } output: Enter number of rows: 5 Program 1.35: Program to print pyramid using numbers. 1 232 34543 4567654 567898765 include using namespace std; Ant main() { int rows, count = @, count = 9, k = 8; cout << "Enter number of rows: "; cin >> rowss (Object orlnted Programming Using Co+ 150 Principles of Cec Oriented Programming \ for(int 4 = 1; 1 <= rows; +41) \ { for(int space = 4} space <= rows-£; ++space) | ¥ € cout << * "3 i +eounts | > while(k I= 2*1-1) € 4f (count <» rows-1) { cout << Stk <<" "5 ++counts + else { tecountts cout << itk-2*countt << y ks } count = count = k = @5 cout << endl; ¥ j return @5 y output: Enter number of rows: 5 1 232 34543 4567654 567898765 Program 1.36: Inverted full pyramid using *. include { using namespace std; int main() 4 } int rows; cout << "Enter number of row cin >> rows; for(int i= rows; i >= 1; =i) + for(int space = 95 space < rows-1; ++space) cout <<" "5 Objact Oriented Program.ning Using Cre 131 Principles of Object Oriented Programming for(int j= 4; j <= 244-2; +49) cout using namespace std; int main() { Int rows, coef = 1; cout << "Enter number of rows: cin >> rows: for(int i = @; i < rows; i++) { for(int space space <= rows-i; space++) cout <<" "5 for(int j = 05 j <= 45 j++) { it (J == @ || i == 0) coef = 15, alse coef = coaf*(i-J+1)/33 cout << coef cc" "; } cout << endl; y return 05 } Output: Enter number of rows: 5 Object Oriented Programming Using Cr 152 Princip of Object Oriented Programming Program 2.38: Program to print Floyd's Triangle. 1 23 456 . 78.916 #include using namespace std; int main() t Aint rows, number = 13 cout << "Enter number of rows: "; cin >> rows for(int i= 1, 4 <= rows; i+) { for(int § = 1; J using namespace std; Ant main() { Ant numa nun2, Lem, ged, temp, prod,ni,n23 do { cout<<"\nénter the two positive num: cin>>numi>snun2; ? while(nuna> ny while(n I= @) { + remainder = nXi0; reversedNunber = reversedtiumbert1@ + remainder; n f= 105 } cout << "Reversed Number = << reversedNumber; return 85 . Ouxput: i Enter an integer: 123 is Reversed Nunber = 321 Program 7.41: Program to make a simple calculator to add, subtract, multiply or divide using switch case. #include using namespace std; int main() t int first, second, add, subtract, multiply Float divides cout << “Please enter tuo intege cin >> Firsts cin >> second; Object Oriented Programming Using Crt asa add = first + second; subtract = first - second; multiply = first * second; divide = first / (float)second; //typecasting cout << endl <<"Sum = " << adds cout << endl <<"Difference = " << subtract) cout << endl <<"Multiplication = " <¢ multiply; cout << endl <<"Division = * << divides return 95 } output: Please enter two integer: 109 50 Sun = 150 Difference = 50 Multiplication = 5000 Division = 2 ‘Program 1.42: program to calculate area of circle. #include using namespace std; Sint main() { Float ryzreas cout<< "\nEnter radius of circle : "3 | cinoors area = 3.14%r*r3 coutc<"Area of circle : "<> lengths cout << “Enter breadth of rectangle : cin >> breadth; // Formula to calculate area of Rectangle area = length * breadth; cout << "Area of rectangle = return 8; << area; Output i Enter length of rectangle : 5 | Enter breadth of rectangle : 10 Area of rectangle : 52 Principles of Object Oriented Programming Object Orlonte 4 Programming Using C++ 1s: Principles of Object Oriented Programming BW Scope Resolution Operator (::) “e Cé+ language supports a mechanism to access a global variable from a function in which a local variable is defined with the same name as a global variable, Its achieved using the scope resolution operator, + The scope resolution operator is denoted by pair of colons (:). + The syntax is as follows: #2 vaniable_nane; Program 1.44; Program for scope resolution operator. #include using namespace stds int int main() { int a=i55 coutc<"\n Local ax"a>>bj } void T::putdata() { coute<"\na=" #includecstrings using namespace std; | Ant main() { char *xs x = aew char[10]5 cout<<“Enter String:"; . cinooxs coute<"\n The string is:"< «5, Easy to Sort Data: Easily short the data using swapping technique. 4, Code Optimization: Less code is required, one variable can store numbers of value. * qhe number of subscripts of an array decides the dimension of an array. Based on the dimensions, arrays can be classified as single-dimensional arvays and multi-dimensional arrays. Single-Dimensional Array «When the elements in an array are referenced by a single subscript, then the array is called a one- dimensional array. One-dimensional array is also called as single dimensional array or linear array. Declaration of Single-dimensional Array: © Aone dimensional array is the simplest form of an array that requires only one subscript to access an array eler-ent. Like an ordinary variable, an array must have been declared before it is used in the program. ©The syntax for declaring a single-dimensional array is given below: data_type array_nane(size); « Forexample, an array marks of type int and size five can be declared using this statement. int marks[6]3 Initialization of Single-Dimensional Array: Initialization as the name suggests means assigning initial values to the elements of array. Array can be initialized only after is declared. «After the array name equal sign (-) can be put and a list of comma-separated values is written within the braces. + ‘The syntax for initializing an array at the time of its declaration is given below: value n}; data_type array_name[sizel=(value 1, value 2, « © The values are assigned to the array elements in the order in which they are listed. That value 2 and valuen are assigned to the first, second and n™ element of the array, respectively. + Forexample, the array marks can be initialized while declaring using following statement, int marks [6}=(72,63,49,58,82,54)5 ‘Accessing Array Elements: « Anelement is accessed by indexing the array name. This is done by placing the index of the element within square brackets after the name of the array. © Once, an array is declared and initialized, the values stored in the array can be accessed any time. = Back individual array element can be accessed using the name of the array and the subscript value, «Every element in an array is associated with a unique subscript value, starting from 0 to size-1 where, size refers to the maximum number of elements that can he stored in the array. «The syntax for accessing the values stored in a single-dimensional array is given below: value 4, array_name [subscript] + For example, the elements of the array marks can be referred to as marks [0], marks [4], marks [2], marks [3], marks [4] and marks [5], respectively. © The memory representation of the array marks is shown in Fig. 1.21. marks) marks(i) marks(2) marks(3} _marks(4] _merksi6) aoe (2005. «20072008201 2018 Fig. 1.21: Memory Representation of Marks Array Object Oriented Prograruming Using C++ re Principles of Object Oriented Programming Program 1.47: Program to store and calculate the sum of 5 numbers entered by the user using arrays, include using namespace std; int mein() { int numbers [5], sum = @; cout << “Enter 5 numbers: *; // Storing 5 number entered by user in an array // Finding the sur of numbers enter for (int 3 = 0; 4 < 5; +44) { : cin >> numbers[i]3 sun += nunbers(i}; y cout <<¢ “Sum =" << sum << endl return 05 y Output: Enter 5 numbers: 5 3.24.4 Sum = 15 : h Program 1.48; Program to sort the array elements. Hincludeciostream> ‘Ancludecionanip> —__//for setw() using nanespace std; int maing) { const int size = 6; //declaring size of array int num{size], temp; //declaring an array coute<"Enter six elements of array"<<"\n"; for(int i-9j4>num[]3 for(int inO;4uml3}) { ‘tenp=nun[ i]; num[i}=num[5]5 //Anterchanging nun[j}=temp; Hlarray elenents } y cout<<"Elenents of sorted array are: \n"; for(int 1=0;i¢size;i++) coutsales(4][3]j //read monthly sales total¢esales[i] [J]; /{calculate total } Ulend of for 3 coutcc"\nTotal Sales of Publishers is:" 1g namespace std; main() int a[.a][10], trans[1e][18], , ¢) tJ cout << “Enter rows and columns of matrix: "; cin >> >> 3 // Storing elenent of matrix entered by user in array af]{]- cout <¢ endl <¢ “Enter elenents of matrix: " << end for(i-= 85 4 < rj ++i) for(j = 85 3 < c3 +3) € cout <<. "Enter elements a" > alS][515 + // Displaying the matrix a[][] cout << endl << “Entered Natrix: for(i = 85 4 < rp +44) for(j= @; J ccs +49) #includeciomanip> //for setw() using namespace std; int main() ¢ int mat1[3][3]=({4,2,3}, //initializing first matrix (3,2,7), (56,45 int mata[3]{3]=(2.4,7}, //initializing second matrix B14), : (53,105 int mat2(3]{3), 4,93 For (4-0 ;ic3si++) //calculating sum of two matrices for(j=055<35 J++) //and storing in third matrix mat3[i)[J) = mati[4](J] + mat2[i}{4]5 coutec" The resultant matrix is:\n*; For(se054<3;44+) //éisplaying result matrix ‘ ‘ For(j=0;5<3;5++) /fcourcesetw(4)cemat3(4][3]; coutecmat3[i][J]<<" "5 coute using nawespace std; define MAX 100 Ant: main() { Harray declaration int arr[MAX]; int nyt,J3 int temp; [read total nunber' of elenents to read coutc<"Enter total number of elenents to rea cin>on; Ii check bound Af(m<@ || m>MAK) { coutc<"Input valid rangel !!"arr(5]) { ‘temp =arr[i]; arr[ilearr[J, are[j]=temp; } t //print ‘sorted array elenents cout<<"Sorted (Ascending Order) Array elenents:" Besides C-strings, C++ also defines a siring class, named string to offer Object-Oriented (00) approach to string handling. Initializing Strings: ‘* string in C++ is declared and initialized in the same way as a character array, The general syntax for initializing a string at the time of its declaration is given below: char string nane[size]="value"; * The following declaration and initialization create a string consisting of the word "HELLO". To hold the nuil character at the end of the array, the size of the character array containing the string is one more than the number of characters in the word "HELLO." Principle of Object Orlanted Programming char greetings] = ('H', 'E', 'L', 'L', ‘0°, ‘\e"}; © Ifwe follow the rule of array initialization, then you can write the above statement as follows: cha greeting[] = "HELLO"; * Fig. .2sis the memory presentation of above defined string in C++. Index. 0 1 2 3 4 5 _Dbject Oriented Programming Using C+ 198, Frinciples of Object Oriented Programming © Actually, we do not place the null character at the end of a string constant. The C++ compiler automatically places the '\O' at the end of the string when it initializes the array. Following program shows an simple program for string. #include using namespace std int main () { char greeting[6] = {'H", cout << "Greeting Nessage: cout << greeting << endl; return 95 Program 1.53: Program to demonstrate string initialization. ‘includeciostream> using namespace std; int main() { char team[]="INOIAN CRICKET TEAM"; float scores[11]={182, 10, 65, 37, 42.6, 33, 11, 16, 8, 6}5 Float average=0; int is for(in0;ictt;it+) averageraveragetscores(i]; averagezavurage/(Float)11; coutc<"average is : "ccaverage; return 05 } Output: ‘Average is : 29.5091 Program 1.54: Program to display a string entered by user. #include using namespace std; int main() { char str[1e]; cout << "Enter a strin cin >> str3 cout << “User entered: " << str << endl; cout << "\nEnter another string: *; cin >>. str cout << "User entered: "ccstrecend; return 0; ? Output: Enter a string: Computer User entered: Computer Enter another string: Tech User entered: Tech Object Oriented Programming Using Cre 167 Principles of Object Orlented Programming a BJ string Class in C++ ‘he standard C++ library provides a string class type that supports all the operations rélated to string, additionally much more functionality. Program 1.55: Program for string class, include include using nanespace std; int main () { string stri = string str2 string: str3; int len ; 11 copy stri into'str3 str3 = stri; cout <¢ “stra: " ce str3 << endl J/ concatenates stri and str2 stra = stri + stra; cou. << "Stel + ste2 : " << str3 ce endl; // total Length of str3 after concatenation len = str3.size(); cout << "str3,size() : Hello" World"; " << Len ce endd; return @; t Outpat: stra: Hello Manipulating Strings & stri + str? : Hellovorld rB.size() : 10 Strings in C++, can be manipulated in different ways. There is a set of pre-defined functions in C+, which are used to manipulate strings in different manners. The pre-defined functions, which are declared in the string.h (or cstring header in new C++ compilers) header file. The string manipulation functions are explained below: 1. streat() function is used to concatenate (combine) two strings with each other. It appends the second string to the end of the first string. ‘Syntax: char *strcat(char *Destination const char *source); 2. strchr() function is used:to scan a string in the forward direction and looking for the first ‘occurrence of a specific character given in the search criteria. Syntax: char *strchr(const char *String, int Character); 3, strrchr() function is used to scan a string in the forward direction and looking for the last occurrence of a specific character given in the search criteria. Syntax: char *strrchn(const char *String, int Character); 4, strstr() function is used to find the first occurrence of « substring in a destination string. Syntax: char *strstr(const char *destination_string, const chan *substring); 5, stremp() function is used to compare two strings with each other either they are equal or not. This function is a case sensitive function and it only compare the same case strings. If both the strings are equal then this function return 0 otherwise, it returns 1 or ~ 1. Following is the general syntax declaration of this function: stremp(const char *stringl, const char *string2); ‘Object Oriented Programming Using C++ 1.58 Principles of Object Orlanted Programming 6. strempi() function is simflar to the stromp function but the main difference is that this function is used to compare two strings with each other without case sensitivity, ‘Syntax: strenpi(const cher *stringl, const char *string2); 7. stricmp() function compares two strings with each other without case sensitivity like the strempi function. 8. stricmp() function is used to compare a portion of the two strings with case sensitivity. Syntax: int strnemp(const char* string, const char*steing2, int num_char); 9.” strniemp() function is also used to compare a portion of the two strings without case sensitivity. ‘Syntax: int stenicmp(const char* stringl, const char* string2); q 10. strepy() function is used to copy a source string to « destination. Syntax: char *strcpy(char *destination, const char * source_string); 14. strncpy() function is used to copy a portion of a source string to the destination. ‘Syntax: char *strncpy(char *destination, const char *source_string, int num_char); 22, strrev() function is used to reverse a given string. The strrev function takes a string value as an argument and returns its reverse, Syntax char * strrev(cher *string); 13, striwn() function is used to convert a string from upper case characters to lower case characters. It takes a string as an argument and converts it to the lower case characters. i Syntax: char *strlwr(const. char *string); fi 414. strupr() function is used to convert a string from lower case characters to upper case i | characters. Syntax: char *strupr(const char *string); 45, strlen() function is used to find the length of a given string. The strlen function takes a string value as an as argument and returns its length as intager. Syntax: int strlen(const char *string); “ Program 1.56; Program for strchr function. #includeciostrean> #includecestring> using namespace std; ant main() { char phoneNio [26] char toSeanch="5"; 7 char ptr; ptr=strchr(phoneNo, toSearch); AF(ptr==NULL) cout<<"Charucter" < #include using namespace std; int main () { char stra[10] = "Hel lo’ chan str2[10} = “World”; char ste3[10}3 Ant len 5 11 copy strt into str3 strepy( str3, stra); cout << "strepy( str3, str1) : " << str3 << endl; // concatenates stri and str2 streat( stri, str2); cout << "streat{ stri, str2): " << str ce endl; // total lenghth of str1 after concatenation Jen = strien(str1); cout << "strien(str1) : return @; b Output: strepy( str3, stra) : Hello streat( str1, str2): HelloWorid strlen(ste1) : 10 Program 1.59: Program that compares two strings using the strcmp function. #includeciostream> #includecstring.h> using namespace std; ant main() { char “First_string, *second_string; int ts coutc<"Enter first string = "; cins>first_string; // read string from the keyboard coutc<"Enter Second string = cin>>second_string; + = strenp(First_string, second_string); if(t==0) << Ten ¢¢ endl; Odject Oriented Programming Using C++ 170 Principles of Object Oriented Programming coutc<"Both strings are equal”; else coutc<"Both strings are not equal"; return @3 y Output: Enter first string = Computer Enter second string = Computer Both strings are equal Program 1.60: Program for strrev function, #includeciostream> #include using namespace sta; void main() char str[20}="12345"; strrev(ste); coute output: 54321 BRAY Array of String * An array of strings in C+, is simply a two-dimensional array of characters where each row represents a string. * ereuienstand the concept of declaring and initializing an array of strings, consider the following statement, char names{3] (8)={ "Ramesh", “"Ranan',, *Mandira” js sececase a Particular string in an array of strings, only one subscript is required, The syntax for accessing a string in an array of strings is given below, array_nane[i] Where {denotes the string number in the array. For example, the second string (that is Raman") in array of strings naines is accessed by names{i]. The memary representation of the array of strings names is shown in Fig. 1.24, 0 names{t] ‘names{2} 2020 Fig. 124: Memory Representation of Names in Array of Strings Program 1.61: Program to reverse each string in an array of strings. #include #includeccstring> //far strrev() function using. namespace stu; const int stre3; “//number of strings const int max=10; //maximum length of each string bjt Orantad Programming Ving Coe in Principe of Obit Oriented Programming int main() { char names[str][max]={"amer", /{declaring and "smith", //iitializing "raman"}; Afarray of strings for(int i=9;icstrji++) { coutc<"Reverse of “ccnemes[i]<<" is "; coutccstrrev(nanes[i])<<"\n"; //reversing strings y return @; nanar + In above example, an array of strings names is declared and initialized with string constants. Each string is accessed using names [i] and the reverse of each string is displayed using the strrev() function, Structures + Unlike C structures, a C++ structure is a collection of variables of different data types undera single name, + Structu-es are used whenever a computer programmer requires binding the same or different types of related data items together into a single entity. * Astructure declaration is a user-defined data type. A structure in C++ is defined as, “a collection of data items of either same or different data type referred to by a common name". The various data items of a structure are known as members (also known as elements) of the structure. + Armay in C++ is used to store objects of the same data type while structures can be used to store data of same type or diferent types. EXZ8] vefining structures * A structure definition in C++ is specified by using the keyword ‘struct’ ie,, followed by braces enclosing the members and there data types. * _Inorder to use the members of a structure in a C++ program, the structure must be defined first. The definition of a structure informs the C++ compiler about the type and the number of the data members forming the structure. * The syntax for defining a structure is given below: struct structure_nane < data_type nenber_nanet; pe ender _nane2} “ype nember_nane3; + Tounderstand how structure is defined, consider following example: struct employee /*deFinition of structure*/ { int. 1D; /*menbers*/ char name[20]; float salary; b i _Oblec Orentad Programming Using C+ 172 Principle of Object Oriented Programming ‘+ Inabove example, a structure employee is defined with three members, namely 1D, name and salary. + While defining a structure in C++, following some important points should always be kept in mind: 4. The member ofa structure cannot be initialized within the structure definition. 2. Astructure member can have the same name as the name of the structure. 3. Two members within a structure cannot have the same name. However, two members of different structures can have the same name. Declaring Structure Variables * Astructure in C++, is a collection of variable which can be same or different types. A structure in C++ can be used in a program only if memory ic allocated to it. * When a structure is defined in a C++ program, the compiler knows about the data type and number of members in the structure; however, memory is hot allocated to the structure at that time, Thus, to ‘use a structure in a C++ program efficiently, a structure variable needs to be detlared. * The syntax for declaring a structure variable is given below: structure_nae structure_varieble; + For example: struct employee [definition of structure*/ { int 105 /uenbers*/ char name [26]; flost salary; Jel e2; [objects or variables of the structure enployee?/ EJ initializing a structure «After declaring structure variables, the next step in C14, is to initialize structure variable. A structure variable may be initialized when itis defined. ‘+ A structure variable can be initialized at the time of its declaration. The syntax for initializing a structure variable is given below: structure_nane structure_variable=(vaiue 1,value2,value3, ..., value n); © The values are assigned in the order in which they are listed ie., valuet is assigned to the first member, value2 to the second member of structure and so on, For example: struct product_record { chan name; Ant preduct_code; int product_quantity; float product_rates w * The members of the structure variable productri of the structure type product_record can be declared and initialized with the help of following statement, i product_record record_Ri={"Maggi", M@1,16,30.20}; Accessing Structure Members | * To access any member of a structure, we use the member access operator (). The member access ‘4p operator is coded as a period between the structure variable name and the structure member that we wish toaccess. * The syntax for accessing the structure members is given bel structure_variable.menber_nane Object Oriented Programming Using S++ 173 Prineplen of Object Oriented Programming ‘Program 1.62: Program to define a structure and initialize its variables. #inclideciostream> using namespace std; struct stud /istructure definition t Ant rolino; int marks; char result[5]3 /arvay within structure ye int main() { stud studla{24,81,"pass*}; J {declaring and initializing //structure variable coutecendl<<"Values of studl are:"< #includectonanip» #includeestring? using namespace std; struct PayRoll { int enptiuiber; // Employee number string name; // Employee name float hours; // Hours worked float payRate; // Hourly pay rate float grossPay; // Gross pay bs . int mair() t struct PayRoll employee; // empioyee 4s a PayRoll structure J1Get Anpute coute<"Enter the employee's number cin>>employee. empNurben; cout<<"Enter the etiployee's name: "; cin.tgnore(); //To sktp the remaining "\n' character getline(cin, omployee.nane); ented Programming Uslig Cr+ 174 Principles of Object Oriented Programming coutc<"Howi many hours did the enpleyee work?"; cin>>enployee. hours; | 1 ourc<*hhat 1s the employee's hourly payRate? *; cin>enployee. payRates // Calculate gross pay ‘employee. grossPayzenployée.hours * employee. payRat // Display results » cout<<*\nHere 4s the enployee’s payroll data:\n"; cout<<*Wane:" #includecenath> 11 Needed for the pow function using namespace std; struct Circle [/oeclares what 2 Circle structure looks like 4 float radius; float diameter; float area; % const double pi = 3.14159; // Constant is made a double to allow for /Tereater precision {int main() : { circle ¢; // defines @ variable chat is a Circle structure Get the circle diameter cout<<"Enter the diameter of a circle: ciino>c. diameter; J/Perform calculations c.radius = c.diameter / 2; F c.area = pi * pow(c.radius, 2.0); ii re rpnvig Wing ae is Prchne Cho ri roinsiig // Output results coute<"Fixed << showpoint"< : #includeciomanip: #includeestrings using namespace std; struct annualcostinfo { float food, medical, license, misc; b struct Petlnfo 1 string name; string type; int age; Annualcostinfe cost} % 1 int main() (Object Oriented Programming Using Cr+ 478 Principles of Abject Orlened Programming pet.nane = "Ton"; pet.type = "cat"; pet.age = 5; pet.cost.food = 250.00; | pet.cost.medical = 150.00; pet.cost.license = 7.00; | { struct Petinfo pet; // vefine a structure variable pet.cost.misc = 50.00; //couts using namespace std; struct Employee * Ant Id; char Nane[25}; Ant Age; 101g Salary; bs Ant main() { int 43 Employee Enpl 3.1; LUstatenent 1 For(im05i<3;4++) t cout << "\nEnter details of " << 441 << " Employee"; cout << "\n\tEnter Employee Id : “; cin >> Emp[i).74; cout << "\n\tenter Employee Name : "; cin >> Emp] Names cout << "\n\ténter Employee Age cin >> Empl] Ag cout << "\n\tenter Employee Szlary : 7 dn >> Enp[4].Salarys ? cout << "\nbetails of Enployees*; For(1903i¢35i4+) cout << "\n"¢¢ Enp[i].Id void display() ss coutc<"Roll no:"< using namespace std; class Square { public: int area(int side) ‘ ‘ a wsidetsides return a3 } voia show() { cout << "The area is." << a3 } private: int side, a; bs int main() : { square x x,area(1@); x.show(); return @5 } output: The area is 100 “ Objects (Creating Objects) * An object is an instance/occurrence of a class. A class provides blueprints for the object. An object is a variab'e of type class. * Once, a class is defined, we can declare variables of that type. In C++, a class variable is called a class object or class instance. + When we createa object of a class: © memory is allocated, ©. constructor is called implicitly, and © memory gets initalised. + The process of creating object is called class instantiation. We cari create object as using following syntax: class_name object_name; oR class_name objectt, object? wu. objectn; For example: student Si stident S1, S25 {/nore than one object of class student * The arother way is, we can create object by placing their name immediately after the class declar: tion. class student { } St, S25

You might also like