0% found this document useful (0 votes)
365 views179 pages

C 4th Semester Rahul

Uploaded by

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

C 4th Semester Rahul

Uploaded by

Ramesh Alli
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 179
fr ee SS / , a Rahul’sV¥ AS PER Topper’s Voice cBcs SYLLABU B.Com. Il Year ITV Sem All Universities in Telangana TATEST EDITION | 2020 OBJECT ORIENTED PROGRAMMING IN C++ 1 Study Manual = Solved Programs us Short Answers 1g Multiple Choice Questions = Fill in the blanks ee 1 Solved Model Papers Pia 2.149! Osmania University Kakatiya University Satavahana University Mahatma Gandhi University Palamuru University Telangana University -by- K. GOPI MSc., B.Ed, ? Rahul Publications __Hyderabad. PI Ph : 66550071, staid B.Com. II Year [V Sem All Universities in Telangana OBJECT ORIENTED PROGRAMMING IN C++ Inspite of many efforts taken to present this book without errors, some errors might have crept in. Therefore we do not take any legal responsibility for such errors and omissions. However, if they are brought to our notice, they will be corrected in the next edition. © Nopart of this publications should be reporduced, stored in a retrieval system, or transmitted in any form or by any means, electronic, mechanical, photocopying, recording and/or otherwise without the prior written permission of the publisher Price®. 149-00 Sole Distributors : ‘®@ : 66550071, Cell : 9391018098 VASU BOOK CENTRE Shop No. 3, Beside Gokul Chat, Koti, Hyderabad. Maternity Hospital Opp. Lane, Narayan Naik Complex, Koti, Hyderabad. Near Andhra Bank, Subway, Sultan Bazar, Koti, Hyderabad -195. wee ee ee "pn ! NX nd OBJECT ORIENTED PROGRAMMING IN C++ STUDY MANUAL SOLVED MODEL PAPERS Model Paper - I 161-161 Model Paper - II 162 - 162 Model Paper - III 163 - 163 SOLVED PREVIOUS QUESTION PAPER May / June - 2018 164 - 164 May / June - 2019 165 - 165 x 1 1 I ! 1 I 1 1 I 1 I I I I I I I I ! 1 I I I I I I I I I I I I I I a UNIT -I INTRODUCTION: Object Oriented Programming: Concepts - Benefits - Languages - Structured vs. Object Oriented Programming. C++: Genesis - Structure of a program ~ Tokens - Data Types - Operators - Control Structures - C vs C+ + - Functions. UNIT - I CLASSES, OBJECTS, CONSTRUCTORS AND DESTRUCTORS: Encapsulation - Hiding - Abstract data types - Object & Classes ~ Attributes - Methods - C+ + class declaration State identity and behaviour of an object. Purpose of Constructors - Default Constructor - Parameterized Constructors - Copy Constructor - Instantiation of objects - Default parameter value - Object types - C+ + garbage collection - Dynamic memory allocation — Meta class / Abstract classes. UNIT - TI OVERLOADING, CONVERSIONS, DERIVED CLASSES AND INHERITANCE: Function and Operator Overloading - Overloading Unary and Binary Operators - Data and Type Conversions - Derived Classes - Concept of Reusability - Visibility modes - Types of Inheritance - Single and Multiple Inheritance - Multilevel Inheritance UNIT - IV POLYMORPHISM, VIRTUAL FUNCTION, STREAMS AND FILES: Polymorphism - Virtual - Classes - Pointer to Derived class - Virtual functions - Rules for Virtual function - Pure Virtual functions - Stream Classes - Types of I/O - Formatting Outputs - File Pointers - Buffer - C++ Stream - Unformatted console l/O operations - Functions: get( ) - put{ ) - formatted console I /O operations - IOS class format functions - Manipulators. UNIT -V EXCEPTION HANDLING AND DATA STRUCTURES IN C++: Exceptions in C+ + Programs - Try and Catch Expressions - Exceptions with arguments. Data Structures: Introduction - Linked list - Stacks - Queues. Neee-2--e ee eee eee Ce ee ee ee ee ee eee ee ee eee eae ae Bay 2 Dawe, dugudud aaa a Bap adedadadedgagadeds cis gi y @ q @ g a y gi y DEDICATED TO LORD SRI VENKATESHWARA PAARSIIIA RSS Ses deaeced AS23529 dadeaea ap ve 5 apapas a ap Saeco ae Pape) Godeeed dievdodococoredodseses dhdosedededodedbcecededededodooeaeced a Tid 1.12 Contents UNIT -1 Introduction to Programming Languages Procedural, Structural and Object Oriented Programming Languages 1.2.1 Advantages of Languages Object-Oriented Programming Paradigm Basic Concepts of Object Oriented Programming Applications of using OOP Genesis ~ History of CPP ications of CPP 1.6.2 A Simple C++ Program tol # 1.6.3 C++ Basic Input/output Basic Structure of a C++ Program C++ Tokens Variables 1.9.1. Scope of Variables Date ‘Types 1.10.1 Primitive Data Types 1.10.2 Derived Data Types 1.10.3 User-Defined Data Types Operators in C++ 19 1.11.1 Operators Precedence in C++ 1.11.2 Expression in C++ Conditional Statements in C++ 1.12.1 Simple if statement 1.12.2 The if ... else statement 1.12.3 Nested if statement 1.12.4 The else if ladder 1.12.5 The Switch Statement 1.12.6 The Conditional Operators: ( ? : ) Page No. DOr naAwonwe 15 16 16 17 18 18 Topic No. 1.13 1.14 1.15 21 2.2 23 24 25 Decision Making and Looping 1.13.1 The while Loop 1.13.2 The do ... while Loop 1.13.3. The for Loop Skipping and Jumping out of Loops Functions 1.15.1 Functions Prototype (Declaring functions) 1.15.2 Function body 1.15.21 Calling a function 1.15.3 Inline functions 1.15.4. Functions Recursivity 1.15.5 Overloaded functions 1.15.6 C vs C++ Functions: Short Question and Answers Choose the Correct Answer Fill in the blanks UNIT - II Encapsulation- Data Hiding Abstract Data Types Objects and Classes 2.3.1 Specifying a Class 2.3.2 Creating Objects 2.3.3. Defining Member Functions State Identity and Behavior of an Object Constructors 2.5.1 Types of Constructors 2.5.2 Constructor Overloading Constructors with Default Arguments 2.6.1 Destructors C++ Garbage Collection Dynamic Memory Allocation (DMA) Meta Classes in C++ 47-51 52 - 52 53 - 53 Rg It ! fopic No. 12 i 10 Abstr fact Clas 2.10.1 oc Is Pure Virt 1" ort Que: a 7 estion - ! ions : se th on ! Fill _ 7 in the = : blanks ” | 1 Introducti aa tion to Fur 3 ! = mand inction and oe : rator Or Overl oe vn - it | ee verloa “ ~ 132 Bin ding “ - - I Type C a | : ! ne & rator Ovi 4 . jerived cl nee = I Exai lasses & ee ° 135 mple for Di a st ; I inheritance 7 a ° | = s uusabil : Ise 1 Defi I Modes of aoe | ws femee rived Class j e Public, we I Types of h — I Short Inheritance ii al | : a rivat 7 a - — ~ fe Inheritan: : : ce | Fill in the a _ 3 \e bi “ 7 lanks “ }41 Pa : : Son _ os in C++ . Virtual ma ; 1 Functi a : : i 7 ic pol | | : : 7 03 - | ism | ‘ ipile-time(: ! - coi early bin q i | a inction ; : - = = 9) VS runt | os = — \time(late : ! 45 introduct = ~ - : : : _ ig) behavit 109 | ee atted and - : : S cl _ a formatted jons and oe )perations : : julators : ! nz | 113 i ua | us | 1 Page No. a x Topic No. 47 4.8 51 5.2 5.3 5.6 5.7 5.8 iv File Pointers Buffer 4.8.1 How does a buffer affect Programming ? 4.8.2 How can it be resolved? Short Question and Answers Choose the Correct Answer Fill in the blanks UNIT-V Enors in C++ Programming Exception Try, Throw and Catch Blocks 5.3.1 Multiple Catch Blocks Exceptions with Parameters Data Structure 5.5.1 Classification / Types of Data Structures Introduction to Linked Lists 5.6.1 Applications of Linked Lists 5.6.2 Types of Linked Lists 5.6.3. Basic operations on a Linear Linked List Stack Data Structure 5.7.1 Basic Operations of Stack 5.7.2 Implementation of Stack (Algorithms) Queue Data Structures 5.8.1 Applications of Queue 5.8.2 Implementation of Queue Short Question and Answers Choose the Correct Answer Fill in the blanks 125 - 127 128 - 128 129 - 129 130 130 131 133 134 136 136 137 138 138 139 145 146 146 149 150 150 155 - 158 159 - 159 160 - 160 7 a ee | LIST OF PROGRAMS ' S.No. Program Name Page No. 1 UNIT -I : 1, Program find sum of 2 given numbers. 10 1.2 Cp program with class 10 13, Program to find simple interest 14 { 4, Program to find area of a circle 14 1 5. © Program on integer arithmetic 24 | 6. Program on floating airthmetic 24 | 7 Program on simple if 26 18. Program on if-else 28 | 9. Program on nested if 29 110. Program on else if lader 31 i 11. Program on switch 32 | 12. Program on Conditional operators: 34 : 13. Program on while loop 35 | 14. Program on do loop 36 115. Program on for loop 38, | 26. Program on user functions 42 1 17. Program on Function Recursion 43 lis 44 1 I UNIT-II | 1. Program to define member function outside the class 58 | 2. Program to define a member function inside the class, 59 13. Program on default constructor. 62 | 4. Program on parameterized constructor. 63 1.5. Program on copy constructor 64 i 6. Program on constructor overloading 65 [7 Program on destructor 67 ' 8. Program to illustrate dynamic allocation 69 | & Program on Meta Class 1 1 10. Program on Pure Virtual Function / Abstract Class 73 ee ee re ee N ' S.No. Program Name Page No. I UNIT- III ! 1 Program on function overloading - type 1 80 | 2. Program on function overloading — type 2 81 13. Program on Unary Operators Overloading 82 ! 4, Program on Binary Operators Overloading 83 15. Program on type casting 86 ! 6. Program on Inheritance 88 17. C++ Program to illustrate access control in inheritance 92 ! 8. Program on single inheritance 94 19. Program on multiple inheritance 95 i 10, Program on multi level inheritance 96 ' 11. Program on hierarchical inheritance 97 ! UNIT-IV ! 1. Program function overloading ~ compile time ploymorphism 105 1 2. Program on operator overloading-compile time polymorphism 106 ! 3. Program on Function Overriding 108 4. Program toVirtual Functions 110 i 5. Program on Pure Virtual Functions ul ' 6. Program on get(); 115, 17. Program on put() 115 ! 8. Program on getline() 16 19. Program on write() 116 ! 10. Program on cin 17 111. Program on cout 117 \ 12. Program on Custom Manipulators 119 t 13. Program to illustrate buffer problem 122 1 14. Program on cin.ignore(numeric_limits) 123 ' 15. Program on cin.synel);" 124 \-----—-—-—----- - - - - vi eer Program on Queue Operations S.No. Program Name Page No. UNIT-V 1. Program on Exceptions 132 2. Program on Multiple catch blocks 133 3. Program on exception with args 135 4. Program on LinkedList Operations 140 5, Program on stack operations 147 6 152 ee eee INTRODUCTION: Object Oriented Programming: Concepts ~ Benefits - Languages - Structured vs. Object Oriented Programming. C++: Genesis - Structure of a program — Tokens - Data Types ~ Operators - Control Structures - C vs C++ - Functions. Ql. Write about classification of different programming languages? Aue Introduction to Programming Languages Since the invention of the computer, many program ing approaches have been tried. These include techniques such as modular programming, top-down programming, bottom up programming and structured programming, A programming language is a language that consists of instructions designed for the computers. Processors only understand machine code as it reaches in two series of 0's and 1's, also known as binary data. Machine code is difficult to understand, and thus various programming languages are being used which are more understandable than the machine code and also provides greater portability. Classification There are various standards based on which the classification of programming languages can be obtained. However, based on the programming paradigm, one can broadly classify them into three categories: Procedural Programming Languages, Structured Programming languages, and Object oriented Languages. 1,0 Machine Language Assembly Language Procedure Programming Object Oriented Programming 1 Rahul Publications B.Com, II YEAR IV SEMESTER OCEDURAL, STRUCTURAL AND OsJECT ORIENTED PROGRAMMING LANGUAGES uss about Structural Programming vs Object Oriented Programming. Q2. Aus: A procedural programming language consists of a set of procedure calls and a set of code for each procedure. A structural programming language emphasizes on separating a program's data from its functionality, On the other hand, object oriented languages are based on entities known as objects. Procedural Programming Languages: These languages code programs in such a way that the program executes statement by statement. 2 ‘These languages are based on the concept defined by the procedure calls. It means that statements are organized into procedures. These procedures are also known as subroutines or functions, Example: Pascal, FORTRAN, COBOL. Structured Programming languages: These are based on the top down methodology in which a system is further divided into compositional subsystem, Structured programming is not only limited to the top down approach. It employs methods using:- Top down analysis for problem solving, Modularization for program structure and organization: Structured code for the individual modules: Example: ALGOL, Pascal, Pl, C, Ada Object oriented Languages: Object oriented program languages are based on the ‘objects’ rather than ‘actions’. This language gives more preference to data rather than logic. ‘An object can be defined as the pairing of a piece of data with the operations that can be performed oon it. It is one of the latest and powerful types Objects are capable of storing information and they can also interact with other objects. The three major concepts defined by a object programming language are:- > — Data encapsulation or data abstraction > Inheritance or derivation > Dynamic or runtime binding Example: C++, C#, java. Rahul Publications UNIT - 1 OBJECT ORIENTED PROGRAMMING IN C++ 1.2.1 Advantages of Languages Q3. What are the advantages of procedural and object oriented programming languages ? Aus: Advantages of these languages are listed below: Procedural Structural Object Oriented 1.Simple, easy implementation of compilers and interpreters 2. The ability to re-use the same code at different places in the program without copying it 3. An easier way to keep track of program flow. 4. The ability to be strongly modular or structured 5. Needs only less memory. 1. Programs are more easily and more quickly written 2. Programs are reliable as fewer organizational and logical errors occur during the initial stages of program development, 1. Improved software development productivity due to modularity, extensibility and reusability. 2. Software Maintenance is improved 3. Reusability helps in faster development of programs, as the language comes worth rich library of objects 4, Lower cost of evelopment 5. Higher quality of software Ossect-ORIENTED PROGRAMMING PARADIGM Q4. Explain about OOP. Aus: ‘The major motivating factor in the invention of object-oriented approach is to remove some of the flaws encountered in the procedural approach OOP treats data as a critical element in the program development. It ties data more closely to the functions that operate on it, and protects it from accidental modification from outside functions. OOP allows decomposition of a problem into a number of entities called objects and then builds data and functions around these objects Object A. aes Data Functions Communication Object C i Functions Object B. Some of the striking features of object-oriented programming are: > — Emphasis is on data rather than procedure, Progiams are divided into what are known as objects. 3} tess) Rahul Publications EAR IV SEMEST B.Com. uh e Data structures are designed such that they characterize the objects. Functions that operate on the data of an object are tied together. Data is hidden and cannot be accessed by external functions. Objects may communicate with each other through functions. New data and functions can be easily added whenever necessary. > Follows bottom-up approach in program design. Object-oriented programming is the most recent concept among programming paradigms and still means different things to different people. We define “object oriented programmings 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.” Q5. Explain the basic principles of OPP ? Aus. Before starting to learn C+ + itis essential that one must have a basic knowledge of the concepts of Object Oriented Programming Some of the important object oriented features are namely: Objects 1 2. Classes 3. Data Abstraction and Data Encapsulation 4. Inheritance 5. Polymorphism 6. Dynamic Binding 7. Message Passing. 1. Objects Objects are the basic run-time entities in an object-oriented system. They may represent a person, a place, a bank account, a table of data or any item that the program has to handle. 2. Classes Acclass is a collection of objects of similar type. For example, mango, apple and orange are members of the class fruit. Classes are user-defined data types and behave like the built-in types of a programming language. Class CAR Properties Methods object _ = Object Ford Toyota Properties Methods Properties Methods Rahul Publications UNIT =I OBJECT ORIENTED PROGRAMMING IN C++ 3. Data Abstraction and Encapsulation The wrapping up of data and functions into a single unit (called class) is known as encapsulation With Encapsulation, The data is not accessible to the outside world. Only those functions which are wrapped in the class can access it. Abstraction refers to the act of representing essential features without including the background details or explanations, Classes use the concept of abstraction and are defined as a list of abstract attributes such as size, weight and cost, and functions to operate on these attributes. Inheritance In OR the concept of inheritance provides the idea of reusability. Inheritance is the process defining a new class (sub) from Existing class (super) It supports the concept of hierarchical classification. For example, the bird ‘duck’, ‘cuckoo! and ‘ostrich’ are part of the class ‘bird’ bird ac] Polymorphism Polymorphism, a Greek term, means the ability to take more than one form. An operation may exhibit different behaviours in different instances. The behaviour depends upon the types of data used in the operation, For example, consider an object shape. A shape may have many forms such as Line, Triangle, Rectangle, and Circle...etc. oe Shape Draw () = [Line Triangle |{ Rectangle |[ Circle | Draw () | Draw() || Draw () |[- Draw 0 Dynamic Binding Binding refers to the linking of a procedure call to the code to be executed in response to the call Dynamic binding (also known as late binding) means that the coxie associated with a given procedure call is not known until the time of the call at run-time. It is associated with polymorphism and inheritance Message Passing Objects communicate with one another by sending and receiving information. Rahul Publications B.Com. 1 YEAR IV SEMESTER The concept of message passing makes it easier to talk about building systems that directly model or simulate their real-world counterparts. A message for an object is a request for execution of a procedure, and therefore will invoke a function (procedure). Q6. Explain the various Applications and Benefits of OOP. has * Main application areas of OOP are: 1. User interface design such as windows, menu 2. Real Time Systems 3. Simulation and Modeling 4, Object oriented databases 5. Aland Expert System 6. Neural Networks and parallel programming 7. Decision support and office automation system ete Benefits of OOP: * The main advantages are > It is easy to model a real system as real objects are represented by programming objects in oor The objects are processed by their member data and functions. It is easy to analyze the user o requirements, » — With the help of inheritance, we can reuse the existing class to derive a new class such that the code repetition is eliminated. This saves time and cost of program. » In OOR data can be made private to a class such that only member functions of the class can access the data, > The principle of data hiding helps the programmer to build a secure program that cannot be invaded by code in other part of the program. With the help of polymorphism, the same function or same operator can be used for different o Purposes. > Large problems can be reduced to smaller and more manageable problems. It is easy to Partition the work in a project based on objects. » It is possible to have multiple instances of an object to co-exist without any interference i.e, each object has its own separate member data and function. (cai) UNIT: 1 OBJECT ORIENTED PROGRAMMING IN C++ Q7. Write a short note on genesis (history) of C++. Anas: The C programming language was devised in the early 1970s by Dennis M. Ritchie an employee from Bell Labs (AT & T) Many other programming languages are derived from the C language. The languages Objective- C and C++ for instance are derived from the C language. Both languages add the “object oriented” element to the language C. One of the most recent languages, that used much of the C language, is Java. The programming language C++ (originally named “C with Classes”) was devised by Bjarne Stroustrup also an employee from Bell Labs (AT&T). Stroustrup started working on C with Classes in 1979. The idea of creating a new language originated from a wish, to do things that were not possible with other languages. He had experience with the language Simula and BCPL. Simula, short for “simulation language,” was the first_ programming language in the late 1960s. So he chose to enhance the C language with Simula-like features, because the C language was fast and portable. Stroustrup did not only use features from Simula but also borrowed features from the languages Ada, CLU, ALGOL 60 and ML. In 1983, the name of the language was changed from C with Classes to C++. (The ++ indicates increment as in C language ). The first commercial release of the C++ language was in October of 1985. In 1989, version 2.0 was released of the C++ language In 1990, “The Annotated C++ Reference Manual” was published. This work became the basis for the future standard, In 1998, a joint ANSI-ISO committee standardized the C++ language. 1.6.1 Applications of CPP Q8. What are the applications of CPP ? Ans: C++ is a versatile language for handling very large programs. It is suitable for any programming task including development of editors, compilers, databases, communication systems and any complex real life application systems. 7 LJ Rahul Publications B.Com. < 11 YEAR’ IV SEMESTER Since C++ allows us to create hierarchy-related objects. We can build special object oriented libraries which can be used later by many programmers. While C++ is able to map the real-world problem properly, the C part of C++ gives the language the ability to get close to the machine-level details. C++ programs are easily maintainable and expandable. When a new feature needs to be implemented it is very easy to add, Since CPP allows inheritance, we can derive a new class (Derived) for code reusability CPP provides different way of data access modifier such as public, private and protected. CPP allows OOP features such as compile time, run time polymorphisms. CPP allows to design 3D games and other application programs. CPP include runtime errors to be handled, so that the program may successfully executed. CPP supports both structured, OOP features in programing, Itis expected that C++ will replace C as general purpose Language with OOP 1.6.2 A Simple C++ Program Q9. Write a sample program in C++. Aus #include Hiinclude this file for cout int main(){ cout<< “Hello, World!” < The above program is used to display a simple message “Hello World”. > The first line // sample program, tells the compiler that, it is a comment which have program description. . > — The second line # include (iostrearn:h), tells the compiler to include iostream header file from é C++ library. > Asin C, every program should have a main function > Next, count is the output function in C++, which displays a message “Hello world” on to the console. > Last line return O, indicates main ( ) is going to end. 1.6.3 C++ Basic Input/output QUO. Write about basic VO in C++. pea? C++ I/O occurs in streams, which are sequences of bytes. If bytes flow from a device likes a keyboard, a disk drive, or a network connection etc. to main memory, this is called input operation and if bytes flow fram main memory to a device likes a display screen, a printer, a disk drive, or a network connection, ete, this is called output operation. 3 Rahul Publications CS unre OBJECT ORIENTED PROGRAMMING IN C++ The header file iostrearn must be included to make use of the input/output (cin/cout) operators. Standard Output function (cout):By default, the standard output of a program points at the screen. So with the cout operator and the “insertion” operator (<<) you can print 2 message oft the screen. Standard input function(cin):In most cases the standard input device is the keyboard. With the cin and >> operators it is possible to read input from the keyboard. QL1. Explain the basic structure of C++ Aus: The general structure of C++ program can be shown in following diagram. Include Statements Class Declaration Class function definition ’ Main program | . > In C++ program, first section is the include section » It contains pre-processor statements to include various header (library) files. » After the include section there is class declaration section. > In class declaration we are defining class, its member variable and declaration for the member function. » Class member function definition section contains the definition of various class member functions. > At last there is a main function, which starts the execution of program and create the object of class. » Generally in C++ program class declaration, class member function definition and main program is written in three separate files. > Class declaration file and class member function definition file is included into the main program to link all of them. > This structure is known as the client-server architecture. > Inclient-server architecture we have client requests for service to server and server provides service to client. > One client can get service from more than one server and similarly one server can provides the service to multiple clients, > Same fundamental is used at here. Classis act as server and program acts as client. 9 (Yd Rahul Publications B.Com. I YEAR IV SEMESTER can be used > Main program (Client) can use more than one class (Server) similarly one class (server) a for more than one program (client). Member Function Server Class Definition | . Main program Client Mmm 1. Program find sum of 2 given numbers. /*Cpp program find sum of 2 given numbers‘/ #include using namespace std; int main() ft int a,b; cout<<“enter any 2 nos\n"; cin>>a>>b; cout<<“sum= “< using namespace std; class person t Rahul Publications UNIT — ee ee = OBJECT ORIENTED PROGRAMMING IN C+ public: void show() { cout<<“hello from class person’; } } int main() { person obj. obj. show(); return 0; (MS sR Ma ers eee mites yh eee Aus : 1.8 C++ Tokens What are various C++ Tokens? Explain with examples. The smallest individual units in a C++ program are known as tokens. A C++ program is written using these tokens, and the syntax of the language. In other words, tokens are one or more symbols understood by the compiler that help it interpret the program code. The following are the different types of tokens: 1. Reserved words(keywords) Identifiers Constants AON Operators a Separators 6. Special symbol 1 Rahul Publications B.Com. I YEAR_1V SEMESTER 1. Keywords The keywords implement specific C++ language features. Key words have a strict meaning as individual tokens to the compiler. They cannot be redefined or used in other contexts. Use of variable names with the same name as any of the keywords will cause a compiler error. The following are the keywords used in C++ programming: auto break int long case char register return const continue short signed default do sizeof static double else struct switch eoum extern typedef union float for unsigned void goto it volatile while 2. Identifiers Identifiers refer to the names of variables, functions, arrays, classes, etc. created by the programmer. They are the fundamental requirement of any language. Each language has its own rules for naming these identifiers. * : Rules: The following rules are common to both C and C++: > Only alphabet characters, digits and underscores are permitted, The name cannot start with a digi > — Uppercase and lowercase letters are distinct. > A declared keyword cannot be used as a variable name. 3. Constants Constants refer to fixed values that do not change during the execution of a program. Like C, C++ supports several kinds of literal constants. They include integers, characters, floating point numbers and strings. Examples for constants: 123 1) decimal integer 12.34 !/ floating point integer 037 // octal integer “C++” // String constant a (/ character constant 12 Rahul Publications eahiel ‘ OBJECT ORIENTED PROGRAMMING IN C++ Constant Numeric Constant Character Constant Integer Real String Character Single Character Constant Constant Constant Constant Example 10 786 ‘a ‘hello’ 4. Operators Operators are the special symbols/tokens used to indicate an action to be taken (usually arithmetic operations, logical operations, bit operations, and assignment operations). Eg t= %)<, >. etc 5. Separators These are tokens used to separaie other tokens. Two commen kinds of separators are indicators of an end of an instruction and also used for grouping Es. ()011 6. Special symbols These are tokens used to for special purpose in programming. Eg. &*,#,% ote Consider the following piece of code If (x<5) “ext; else x=xt10; Here, the tokens that will be generated are Key words if, else Identifier x Constants: 2, 10,5 Operators = Separator: () ) a Rahul Publications eee errr B.Com. Constants Ident mmm 3. Program to find simple interest Cp program find simple interest’/ #include using namespace std; int main() { float p.tir cout<<"enter p,t.r values\n"; cin>>p>>t>>r; cout<<"interest= “<<(p"t*r/100, } Output: a RD Coy Mim 4. Program to find area of a circle /*Cpp program to find area of a circle’/ #include using namespace std; int main() { Separators Special Symbols Operators ILYEAR IV SEMESTER Rahul Publications @) ~ OBJECT ORIENTED PROGRAMMING IN C++ float r; cout<<“enter radius\n"; cin>>r, coute<"Area= “<<3.14164r, Ate EP ILL (eee Cee teats variable? Explain about usage variables in C++. Q13. What Aus: ‘As you probably know, a variable is a named location in memory that is used to hold a value that may be modified by the program. All variables must be declared before they can be used. The general form of a declaration is type verabie tists = [id Ty values a int x; x 10 x= 10; Torr ToIz 2 bytes declares integer variables i, j, | each variable will be assigned 2 bytes of memory Declares a short int variable called 5i. Voy, v, declares a positive integer variables 4i > — declares double type variables balance, profit, loss. If you declare variables along with datatypes, there are 2 advantages suitable memory allocation 2. Same kind f data is stored Here, type must be a valid data type plus any modifiers, and variable_listmay consist of one or more identifier names separated by commas. Here are some deciarations: Int i,j,t; Short int si; unsigned int ui; double balance, profit, loss; Remember, in C/C++ the name of a variable has nothing to do with its type. 15 Rahul Publications ase eee ee eens B.Com. 1.9.1 Scope of Variables Q14. Explain the scope of variables. Aus: Variables will be declared in three basi ILYEAR IV SEMESTER jc places: inside functions, in the definition of function parameters, and outside of all functions. These are also classified as local variables, and global variables. Rules for defining variable name > — Avariable name can have one or > — White space, punctuation symbol > A variable name must begin with more letters or digits or underscore for example : int _myno; Is or other characters are not permitted. a letter. > Variable names cannot be keywords or any reserved words of the C+ + programming language, > C++ isa case-sensitive language. Variable names written in capital letters differ from variables in small letters. For example, the variable name NUMBER differs from the variable name 1.10 Data Types number. Q15. Explain about v Ans: ious Data types it in C++ Data Type refers to the type of the data that a variable can store. A programming language includes certai in kinds of data types to store input data. A program usually contains different types of data types (integer, float, character etc.) and need to store the values being used in the program. C++ language is rich of data types. C++ data types can be broadly classified as: 1, Primitive/ Built in Data Types 2. Non Primitive/ Derived Data Types 3. User defined Data Types C++ Data Types User defined type Built in type Derived type . Structure, Ara) y Union Function Class Pointer Enumeration reference Integral Type void Floating type int char Float double z 16 } ‘chu! Publications ame UNM OBJECT ORIENTED PROGRAMMING IN C++ 1.10.1 Primitive Data Types Q16. Explain primitive data types in C++. Aus: ‘These are primary data types in C++ 1. Integer Data Types : Integers are whole numbers with a range of values, range of values are machine dependent. To control the range of numbers and storage space, C has three classes of integer storage namely short int, int and long int. ‘Syntax to declare integer variables: int ; eg: int num]; short int num2; long int num3; short int ong int 1 Byte 2 Bytes 4 Bytes Floating Point Data Types: The float data type is used to store fractional numbers (real numbers) with 6 digits of precision. Floating point numbers are denoted by the keyword float.To extend the precision further we can use long double which occupies 10 bytes of memory space float long double 4 Bytes 8 Bytes 10 Bytes Syntax to declare float variables: float ; float num1, double num2; long double num3; 3. Character Data Type: Character type variable can hold a single character and multi characters(strings). These are declared by using the keyword char. Syntax to declare single char: char ; char ch = ‘a’; @) ‘Rahul Publications B.Com. IL-YEAR_IV SEMESTER Syntax to declare strings: char [size); Char name(25); Pate Use ey i char Single character 8 bits From -128 to +128 Unsigned int Integer,lowervalue 16 bits From -0 to 65535 int Higher value integer 16 bits From -32768 to 432768 unsigned long Larger integer 32 bits 0104.39 long Signed Larger integer 32 bits -2.1SE9 to +2.15E9 float Number with 32 bits 3.4E-38 to 3.4E+38 decimal point double Larger number with 64 bits 1.7€-308 to 1.7E+308 decimal point > Signed data types can hold both positive and negative. Unsigned data types can hold large positive values. 1.10.2 Derived Data Types QI7. Explain about derived data types. Ans: 1. Arrays: An array is a collection of variables of the same type that are referred to through a common name. 2. Functions: A function is a group of statements that is executed when it is called from some point of the program. The following is its format: type name ( parameter], parameter2, ...) { ) statements } Pointers: A pointer is a variable that holds'a memory address of another variable. Referencing variables: The ‘&’ operator is used to reference an object. 1.10.3 User-Defined Data Types Q18. Explain about user derived data types. Aus; 1. Structures and Classes: Struct and union data types are used to group variables of different data types. Rahul Publications e one OBJECT ORIENTED PROGRAMMING IN C++ C++ also permits us to define anther user-defined data type known as class be used to declare variables. The class variables are known as objects, which are the central focus of abject-oriented programming, 2, Enumerated Data Type: An enumerated data type is another user-defined type which automatically enumerates (creates) a lst of words by assigning them values 0,1,2, and so on Examples: enum shape { circle, square, triangle }; enum colou { red. blue, green, yellow}; Note : The ISO/ANS! C++ Standard has added certain new data types to the original C++ specifications. One of the new data type is: bool. Syntax : In C++, the data type bool has been introduced to hold a boolean value, true or false.The values true or false have been added as keywords in the C++ language. bool bl = true; _// declaring a boolean variable with true value 1.11 Operators in C++ Q19. Write a short note on various Operator: Aas: An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations C++ provides a rich set of operators to manipulate variables. Arithmetic Operators 1. Arithmetic Operators 2. Relational Operators 3. Logical Operators 4. Conditional Operators 5, Assignment Operators 6. Bitwise Operators 7. Increment, Decrement operators 8. Special Operators CPP OPERATORS Arithmetic Operators Bitwise Operators © Conditional Operators IneDec @ Operates ©) Special Operators Assignment Operators Relational Operators Logical Operators © 19 Rahul Publications See een B.Com. i YEAR IV SEMESTER 1, The Arithmetic Operators: Arithmetic operators are used in mathematical expressions in the same way that they are used in algebra Assume integer variable A =10 and variable B = 20, then Operator | Description Example : + Addition operator A + Buill give 30 . Subtraction operator Multiplication operator ! Division operator % Modulus operator A- Bill give -10 A* Buwill give 200 B/Awill give 2 B% Awill giveO | 2. The Relational Operators / Comparison Operators: These operators compare relation between two operands, Assume variable A holds 10 and variable B holds 20, then: Operator | Deser Example Checks if the values of two operands are equal or not | (A == B) is not true. !s Checks if the values of two operands are equal or not} (A != B) is true 5 Checks if the value of left operand is greater than (A > B) is not true. Checks if the value of left operand is greater than or = | (A >= B) is not true. < —__ | Checks if the value of left operand is less than (A < B) is true. Checks if the value of left operand is less than or = (A <= B) is true. 3. The Logical Operators These operators are used to return logical value of the expressions. Assume Boolean variables A holds true and variable B holds false, then: Operator | Description Example && Logical AND operator tl Logical OR Operator ! Logical NOT Operator (A && B) (411 B) A && B) 4. The Assignment Operators The assignment operator gives a value to variable. There are various short hand operators listed below. ) Rahul Publications une! OBJECT ORIENTED PROGRAMMING IN C++ Operator | Description Example Simple assignment C =A + Buill assign value of A + B into C Short hand assignment | C += Ais equivalent toC = C +A Short hand assignment | C-= Ais equivalent to C = C-A Short hand assignment | C *= Ais equivalent toC = C*A = Short hand assignment | C/= is equivalent toC = C/A a Short hand assignment | C %= Ais equivalent to C = C % A 5. Conditional Operators (? : ) Conditional operator is also known as the ternary operator. This operator consists of three operands and is used to evaluate Boolean expressions. Variable = (expression) ? Value if true: Value if false Eg: x= (a>b)?a:b; 6. — The Bitwise Operators C defines several bitwise operators, which can be applied to the integer types, long, int, short, char and byte. Bitwise operator works on bits and performs bit-by-bit operation. The following table lists the bitwise operators: Assume if a = 60; and b = 13; Operator Description Example & Bitwise AND (A & B) = 0000 1100 | Bitwise OR (A | B) = 0011 1101 a Bitwise XOR (A * B) =0011 0001 ~ Bitwise Ones Complement | (~A ) will give -61 << Bitwise Left Shift Operator. | A << 2 = 1111 0000 >> Bitwise Right Shift Operator | A >> 2 = 1111 >>> Shift right zero fill operators | A >>>2=s 0000 1111 7. Increment Decrement Operators These operators are used to increase or decrease a variable by 1 unit If B=20 then we get: Operator | Description Example ++ Increment - Increases the value of operand by 1 | B++ gives 21 — Decrement - Decreases the value of operand by 1 | B-~ gives 19 i - Rahul Publications B.Com. ILYEAR_IV SEMESTER : 8. Special Operators ¢ \ (i) Size of Operator: This operator is used check memory size of a variable. ' Int mn; m=sizeof(n); (ii) Dot Operator: The dot (.) operator is used to access the Structure members variables. e.g Xa=l: X.disp (); 1.11.1 Operators Precedence in C++ 20. Explain Operator precedence in C++. Ans: Operator precedence determines the grouping of terms in an expression and decides how an expression is evaluated Certain operators have higher precedence than others, for example, the * operator has a higher precedence than the + operator. > Operators/expressions contained within pairs of ( ) are evaluated first. Parentheses are said to be at the “highest level of precedence.” Unary operators are applied next. If an expression contains several unary operations, operators are applied from right to left > Multiplication and division are performed next. Operator Precedence Group Associativity Operator Precedence (0), 0, postfix +++, postfix — Left Highest unary +, unary -, prefix ++, prefix —, ~, tight (type), new Left *h Left +- Left <<, >>, >>> Left < <=, >, >5, instance of Left . Left Left && Left Wl Left 2 Left right Lowest WwW Rahul Publications UNIT - 1 OBJECT ORIENTED PROGRAMMING IN C++ Example: Consider the expression: 1+2*3 the value is 7 On the other hand if the expression is: (1+2)*3 the value will be different i.e. 9, because the expression in parentheses gets executed first. 1.11.2 Expression in C++ Q21. Write about Expression in C++. Aus “An Expression in C++ isa form when we combine operands (variables and constant) and C++ Operators.” (or) “Expression is a combination of Operands and Operators.” expr 3x+5=20 There are four types of expressions 1. Constant Expressions 2. Arithmetic expression 3. Relational expression 4, Logical expression 1. Constant Expressions: Constant Expressions consist of only constant values, Examples: 20+15/2.0 2. Arithmetic Expressions: “An expression in which arithmetic operators are used is called arithmetic expression”. For example an arithmetic expression is look just like that a+b=5 Modes of Arithmetic Expressions: Integer arithmetic, Real arithmetic, Mixed mode arithmetic Integer arithmetic mode In this mode when arithmetic operation perform by using integer values it always result an integer value. for example: a*b=25, a/b=1, atb=10, ab=0 Real arithmetic mode In this mode when a arithmetic operation is performed by using floating point numbers. It always result a floating value. E.g: ab=2.0, a+b=15.0, a-b=5.0 Mixed arithmetic mode In this mede when an arithmetic operation performed on float and integer values.It always result a float value.For example: a=10 , b=5.0 a*b=50.0, 3. _ Relational expressions: An expressions in which relational operators are use is called relational expression." Eg: A == B,A!=B 23 Rahul Publications B.Com. ILYEAR_ IV SEMESTE, 4. Logical Expression: “A Logical operator with constants and variables makes logical expression or An expressions in which logical operators are use is called logical expression.” Examples: 10) && (j > 0), ((x + y) <= 15) || (i == 5) mm 5. Program on integer arithmetic /*Cpp program on integer airthemetic*/ #include using namespace std, int main() // Declare and initialize variable a and b inta= 11, b= 4, cout<<‘a + b ="<< a + b< using namespace std; int main() { int a,b; cout<<"enter any 2 nos\n"; cin>>a>>b; i(a>b) coul<y) { if (x>2) { cout<<"xis big”; } ele { ‘statements; t @) ul Publications » unt OBJECT ORIENTED PROGRAMMING IN C++ Ifthe concition-1 is false statements will not be executed; otherwise it continues to perform the second test. If the condition-2 is true, the statements will be evaluated: [MI 9. Program on nested if Unested if #include using namespace std; int main() { int a,b; cout<<"enter any 2 nos\n’; cin>>a>>b; it(al=b) { it(a>b) { cout< 79) grade = “Honours”; cbse if (marks >59) grade = “First Division”; else if (marks > 49) grade = “Second Division”; else if (marks > 39) grade = “Third division”, else grade = “Failed [Sarementa] : statement ( Rahul Publications a UNITE ENTED PROGRAMMING IN C++ OBJECT ORI MMM 10. Program on else if lader 1 else if lader include using namespace std; int main t int n; cout<<"enter a no\n’, cin>>n; if(n>0) cout< The variable used in a switch statement can only be short, int, or char. > You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon. > The value for a case must be the same data type as the variable. > When a break statement is reached, the switch terminates, and the flow of control jumps to the next line following the switch statement. Not every case needs to contain a break. If no break appears, the flow of control will fall through to subsequent cases until a break is reached MEI 11. Program on switch switch demo #include using namespace std; int main f char ¢; () Rahul Publications Cae OBJECT ORIENTED PROGRAMMING IN C++ cout<<“enter a alphabetn’. cin>>¢; switch(c) { case ‘a’ case 'e! case 7: case ‘0! case ‘ucout<<"vowel’:break; default:cout<<"consonant", J return 0; } Output: 1.12.6 The Conditional Operators: ( ? : ) Q28. Explain the use of conditional operators ? Ana: The conditional operator in C++ is also known as ternary operator because it takes three arguments. The conditional operator evaluates an expression and returns either true ot false Syntax: (Condition)? result1: result2; If the condition is true, result] is returned else result2 is returned Syntax2: (Expression1)? Expression2: Expression3; Based on the value of Expression1, Expression2 or 3 will be executed. ) 2 cout< <<“Both are same”: cout<<“Not same’ 33 ‘Rahul Publications B.Com. IL YEAR IV SEMESTER WI 12. Program on Conditional operators: Conditional operators’/ Void main() { int a= 10, int ¢; c= (a using namespace std; int main() { int n,i=4; cout<<“how many times\n’; cin>>n; while(is=n){ cout<<‘welcome\n", itt; y, return 0; } Output: () Rahul Publications B.Com. IL YEAR_IV SEMESTER 1.13.2 The do Q31. Exp! Ans: A do...while loop is least one time. while Loop the syntax of do loop. ilar to a while loop, except that a do...while loop is guaranteed to execute at Syntax: The syntax of a do...while loop is: do { //Statements }while(Boolean_expression); v [_B0ay of Loop x a Ke Goren ea false 1 tatement just! below Loop y lowchart of do...while loop dot cout<<“value of x :” + x; xt; }while( x < 20 ); - Hm 14. Program on do loop U1 math table #include using namespace std; int main { int n,i=1; t) Rahul Publications UNIT - 1 cout<<"enter a number\n’: cin>>n; cout<<"math table of "< using namespace std; int main() f int a,b,¢,nj: a0: b=1, cout<<"enter how many terms\n’; cin>>n; cout< void main ( ) { int x ; for (x = 1; x < = 20; x +4) count <<“hello\n"; if (x = = 10) break, } The continue Keyword Q34. Explain the use of continue. Ans The continue keyword can be used in any of the loop control structures. It causes the loop to immediately jump to the next iteration of the loop. > In for loop, the continue keyword causes flow of control to immediately jump to the update statement. In a while loop or do/while loop, flow of control immediately jumps to the Boolean expression. Syntax: continue; e.g: forl x=1;x<=15xt+ ) { Hi 5 or x==10) continue; } Program on continue I] continue #include void main () { intx; for (x = 1; x < = 10;x ++) { if (x = = 6) continue else count <<1<<""; } 39 Rahul Publications B.Com. ILYEAR_1V SEMESTER Q35. What is a function ? Explain its steps ? Ans: Functions allow to structure programs in segments of code to perform individual tasks. In C++, a function is a group of statements that is given a name, and which can be called from some point of the program. The most common syntax to define a function is: type function-name ( parameterl, parameter?, ...) { statements b Where: type is the type of the value retumed by the function. function-name is the identifier by which the function can be called. parameters are the variables used inside a function, statements js the function's body. It is a block of statements. eg: int addition (int a, int b) { int r; raat; return 1; } In the example above, the addition function may be called from main ) as: int addition (int a, int b) z = addition ( t . ! ve The result is 8. 1.15.1 Functions Prototype (Declaring functions) Q36. Explain the syntax to declare a function. Ana: The prototype of a function can be declared without actually defining the function completely. Once declared, it can be called later. The declaration shall include the return type and function name and arguments. Rahul Publications UNIT - | OBJECT ORIENTED PROGRAMMING IN C++ Retrun type function name (arguments); Example: int addition (int a, int b) » In the above declaration int is the return type of the function > addition is the name of the function > _inta, int b are the variables used inside the function 1.15.2 Function body Q37. Explain the syntax to desire function body. Aus Once declared, the function body is defined with statements which could be called later in another function. > The following syntax can be used to define function body. Returntype functionname(arguments) { I body ; } Example: int addition (int a, int b) { intr, r=atb; retum 5; } > the above block defines body of addition function, so that a + b is calculated and stored in y. > the return statement return value of g (sum of a, b) 1.15.2.1 Calling a function > A function is called after it is declared and defined > A function may be called with its name and number of arguments > A function may be called by another functions for execution Syntax to call a function function name (arguments) ; Eg: int main ( ) { count< using namespace std; int main() { void show(); cout<<"1.main is calling show()\n show); return 0; } void show() { cout<<"2.show()-am called from main’; Y (1.15.3 Inline functions Q38, What is an inline function in C++? Ans: C++ inline function is powerful concept. If a function is inline, the compiler places a copy of the code of that function at each point where the function is called at compile time. Any change to an inline function could require all clients of the function to be recompiled. For example, the Add function may be declared inline as: 1 inline int Add (int & a, int & b) 2f 3 retum a+b; ) @) Rahul Publications Unite TED PROGRAMMING IN C++ OBJECT ORIEN’ 1.15.4 Functions Recursivity Q39. What is meant by function recursivity ? Ans Recursivity/Recursion is the property that functions have to be called by themselves. Itiis useful for some tasks, such as sorting elements, or calculating the factorial of numbers. For example, in order to obtain the factorial of a number (n!) the mathematical formula would be: nl = n* (nel) * (n-2) * (n3)..* 1 More concretely, 5! (factorial of 5) would be: 51=5°4*3*2*1= 120 And a recursive function to calculate this in C++ could be mI 17. Program on Function Recursion: 17 factorial calculator #include ong factorial (long a) f if(a>1) retum (a * factorial (a-1)); else retum 13) int main () { Jong number = 9; cout << number << *! = * << factorial (number); return 0; } Output: _9/ = 362680 1.15.5. Overloaded functions Q40. Write about functions overloading ? Aus: In C++, two different functions can have the same name if their parameters are rent; > A function may be declared, declined more than once, but by increasing / decreasing function arguments > — The process of increasing / decreasing function arguments is called overloading Us Rahul Publications ————s com. Example int add (int x, int y) { count <<"< (b) :< (< (a) 10, _______are the variables used inside a function. [a (a) parameters (b} tokens (©) cases (d) literals Rahul Publications UNITE OBJECT ORIENTED PROGRAMMING IN C++ Fillin the blanks 1 OOP means 2 refers to the act of representing essential features. 3. means the ability to exist in more than one form. 4. C++ language way devised by 5. Enum Data Type is data type 6. sa combination of operands and operators 7. break and continue are called as __ statements. 8. Function declaration may also referred as 9, keyword is used to declare an inline function. 10. is the process of calling a function by itself ANSWERS Object oriented programming Abstraction Polymorphism Bjame Stroustrup userdefined jumping prototype inline 1 2 3. 4 5 6. Expression 7 8 9 V 0. Recursion Rahul Publications Eye aa ERs Tay EPA Ta CLASSES, OBJECTS, CONSTRUCTORS AND DESTRUCTORS: Encapsulation - Hiding - Abstract data types - Object & Classes ~ Attributes - UNIT | Metnoas - c++ class declaration - State identity and behaviour of an object. | Purpose of Constructors - Default Constructor - Parameterized Constructors = ll Copy Constructor - Instantiation of objects - Default parameter value - Object types - C++ garbage collection - Dynamic memory allocation ~ Meta class / Abstract classes. eT z ETS CLASSES, OBJECTS, CONSTRUCTORS AND DESTRUCTORS 2.1 Encapsutation- Data HIDING Ql. Write a short note on Encapsulation & Data hi Aus Encapsulation is an Object Oriented Programming concept that binds together the data and functions that manipulate the data. > Italso keeps both safe from outside interference and misuse. > Data encapsulation led to the important OOP concept of data hiding Data encapsulation is a mechanism of bundling the data, and the functions that use them and data abstraction is a mechanism of exposing only the interfaces and hiding the implementation details from the user. ~ C++ supports the properties of encapsulation and data hiding through the creation of user-defined types, called classes. We already have studied that a class can contain private, protected and public members, By default, all items defined in a class are private. For example “ class Box { public: double getVolume(void) { retum length * breadth * height; } private: double length; _// Length of a box double breadth; _// Breadth of a box double height; _// Height of a box The variables length, breadth, and height are private. This means that they can be accessed only by other members of the Box class, and not by any other part of your program. This is one way encapsulation is achieved. ose) ions unit tt OBJECT ORIENTED PROGRAMMING IN C++ Asstract Data Types Q2. What is meant by Abstract Data Type? Ans: Abstract Data type (ADT) is a type (or class) for objects whose behavior is defined by a set of value and a set of operations. The definition of ADT only mentions what operations are to be performed but not how these operations will be implemented. It does not specify how data will be organized in memory and what algorithms will be used for implementing the operations. Itis called “abstract” because it gives an implementation independent view. The process of providing only the essentials and hiding the details is known as abstraction. The user of data type need not know that data type is implemented, for example, we have been using int, float, char data types only with the knowledge with values that can take and operations that can be performed on them without any idea of how these types are implemented. So a user only needs to know what a data type can do but not how it will do it. ‘We can think of ADT as a black box which hides the inner structure and design of the data type. Examples for ADT, namely List ADT, Stack ADT, Queue ADT. List (Array) ADT A list contains elements of same type arranged in sequential order and following operations can be performed on the list. Stack ADT A Stack contains elements of same type arranged in sequential order. All operations takes place at a single end that is top of the stack and following operations can be performed: Queue ADT ‘A Queue contains elements of same type arranged in sequential order. Operations takes place at both ends, insertion is done at end and deletion is done at front. Following Q3. Write about classes and objects on C++ ? Aus: Extensions to Structures: > C++ supports all the features of structures as defined in C, But C++ has expanded the capabilities further to suit its OOP philosophy. > It attempts to bring the user defined types as close as possible to the built-in data types, and also provides a facility to hide the data > A class is similar to a structure but, the only difference is by default, the members of a glass are privete, while, by default, the members of a structure are public 55 Rahul Publications B.Com. ILYEAR_IV SEMESTER » There is very little syntactical difference between structures and classes in C+ + and, therefore, they can be used interchangeably with minor modifications. > Since class is a specially introduced data type in C++, most of the C++ programmers tend to use the structure for holding only data, and classes to hold both the data and functions. 2.3.1 Specifying a Class Q4. Explain how a class in specified in C++. Aus: A class is a way to bind the data and its associated functions together. It allows the data and functions to be hidden, if necessary, from use. When defining a class, we are creating a new abstract data type that can be treated like any other built-in data type. Generally, a class specification has two parts: 1. Class declaration 2. Class function definitions The general form of a class declaration is: class class_name { private: variable declarations; function declarations; public: variable declarations; function declaration; h The class declaration is similar to a struct declaration; the body of a class is enclosed within braces and terminated by a’semicolon. > — The class body contains the declaration of variables and functions. ‘These functions and variables are collectively called class members. > They are usually grouped under two sections, namely, private and public which shows the scope of each member. Example: By default, all members of a class declared with the class keyword have private access for all its members. Therefore, any member that is declared before any other access specifier has private access automaticaly 56 Rahul Publications va OBJECT ORIENTED PROGRAMMING IN C++ For example: class Rectangle { private: int width, height; public: void set_values (int,int); int area (void); GF Rectangle rect; Here, Rectangle is a class and an object (ie., a variable)of the class is rect. This class contains four members: 2 data members of type int ( width and height) with private access and | 2 member functions set_values and area with public access. 2.3.2 Creating Objects | Q5. Explain the syntax to create an object in C++. Ana: Once a class has been declared, we can create variables of that type by using the class name as: Classname object name; For example, Rectangle rect; Rectangle is the class name (i., the data type), whereas rect was an object (variable of type class Rectangle). Accessing Class Members: The foll ing is the format for calling a member function: Object name.function name (actual -arguments); rect.set_values (3,4); myarea = rect.area(); For example: rect set_values (3,4); myarea = rectareal); 2.3.3 Defining Member Functions Q6. Explain the syntax to define member functions in a class, Ans; Member functions can be defined in two places: 1. Outside the class definition. 2. Inside the class definition. Rahul Publications B.Com. I YEAR _IV SEMESTER 1. Outside the Class Definitio: Member functions that are declared inside a class have to be defined sepe.ately outside the class. Their definitions are very much like the normal functions. They should have a function header and a function body. Syntax: return- type class-nam: { Function body; ) The membership label class-name :: (scope resolution operator) tells the compiler that the function belongs to the class. For example, void Rectangle::set_values (int x, int y) { : width = x height = } ~ 2. Inside the Class Definition: Another method of defining a member function is to replace the function declaration by the actual function definition inside the class. For example, we could define the item class as: lass Rectangle { int width, height; public: void Rectangle::set_values (int x, int y) { width = x; height = y; } i ME 1. Program to define member function outside the class MU classes example #include using namespace std; class Rectangle { int width, height; () Rahul Publications UNIT - II OBJECT ORIENTED PROGRAMMING IN C++ public: void set_values (int int); int area() {return width*height) BE a void Rectangle:'set_values (int x, int ) { int main () { Rectangle rect; rect.set_values (3,4); cout << “area: * << rect.area(); return 0; i Output: area: 12 Note: 1. Compilers such as Dev c++, Ve++ allows to write header files without -h (#include and name space std should be placed start of c+ +code. 2. A namespace is a container for all the functions used inside the program. WME 2. Program to define a member function inside the class. I defining a member function inside the class include using namespace std; class Rectangle { int width, height; public: void set_values (int x, int y) { width = x; height = y; } int area() di return width*height; } of int main () { Rectangle rect; rect.set_values (3,4); cout << “area: * << rect.area(); retum 0; } @) Rahul Publications I YEAR_ IV SEMESTER Process exited after @.1626 seconds 2.4 State IDENTITY AND BEHAVIOR OF AN OBJECT Q7. Explain state and behaviour of an object. Aas : > — Methods take an Object from one State to Another ‘A method may be called only when an Object is in a selected set of states. ~ Example: File Handler > Open may be called only if state isnot open > Close may be called only if the state is open Conditions: Pre-Condition (Advertised Requirements) execution of function. Post-Condition (Advertised Promises) upon completion of function _— Must be satisfied for proper / guaranteed ) — Guaranteed State of the Object ‘An may communicate with other objects. > Anobject may access other objects’ properties by using inheritance > Multiple objects may exist for a single class. % — Anobject may also used to define class variables as instance variables. > An object may call a same function multiple times, Constructors ate special member of a class. A constructor initializes object of a class. A C++ Constructor is automatically called when an object (an instance of the class) is created. Q8. What is a constructor? Aus > Ithas the same name of the class. > It must be a public member. No Return Values. Default constructors are called when constructors are not defined for the classes. v 7 > — Constructors can be defined either inside the class or outside class. class A, { int x; public: Al); /Constructor k ) Rahul Publications UNIT - Hl OBJECT ORIENTED PROGRAMMING IN C+* class A inti pul A(); //Constructor declared h A:A() _// Constructor i=l; } 2.5.1 Types of Constructors Q9. Write about different types of constructors ? Aus Constructors are of three types 1. Default Constructor 2. Parameterized Constructor 3. Copy Constructor 1. Default constructor: Default constructor is the constructor which doesn't take any argument. | Syntax: class_name () { //Constructor Definition } Example: class Cube { public: int side; Cubel) { side=10; } b In this case, as soon as the object is created the constructor is called which initializes its data members. ‘A default constructor is so important for initialization of object members, that even if we do not define a constructor explicitly, the compiler will provide a default constructor implicitly Ce} Rahul Publications B.Com. IL YEAR IV SEMESTER mm 3. Program on default constructor. 1/ default constructor #include using namespace std; class Cube { public int side; Cube() { side=10; } int main() { Cube c; cout<<‘default constructor is called\n’; cout<<"side= " < using namespace std; class Cube { public: int side; Cube(int x) f side’ } h int main) fi Cube ¢1(10); Cube c2(20); cout <<"param constructor called 1 time cout<<'side= "< using namespace std; class Marks { public: int maths; Moonstructor Marks() { cout << “Inside Constructor’< Garbage collection is the recovery of computer storage that is being used by @ Program when that program no longer needs the storage. a Garbage collection is an automatic memory management f programming languages, such as C++, dava and languages feature in many modern > The programmer is responsible for ensuring that objects they created via new are, deleted via delete. > han object is created, but not destroyed before the last pointer or reference to it goes out of scope, it falls through the cracks and becomes a Memory Leak Unfortunately for C, C+ + and other languages which donot include a GC. It can cause an application or the system to run out of memory and be unable to allocate new blocks of memory. For example, int main() 4! int* variableThatlsAPointer = new int; int variablelnt = 0; delete variableThatlsAPointer;} Here, we created two variables. These objects will be automatically deleted, Dynamic Memory Attocation (DMA) Q14. Explain about DMA. Aus: There are two ways via which memories can be allocated for storing data. 1. Compile time allocation or static allocation 2. Runtime allocation or dynamic allocation of memory. Programmers can dynamically allocate storage space while the p used in 2 steps: rogram is running, dynamic allocation (68 Rahul Publications Vw ll” ISS SS, UNIT - Il OBJECT ORIENTED PROGRAMMING IN C++ | > Creating the dynamic space in memory > Storing its address in a pointer (so that space can be accessed) Mem the use ofory de-allocation is also a part of this concept where the “clean-up” of space. Itis the job of the programmer to de-allocate dynamically created space Memory in your C++ program is divided into two parts: > stack: All variables declared inside any function takes up this memory | > heap: It is the unused memory used to DMA at runtime | -» To allocate space dynamically, use the new operator as: | int * p; I! declares a pointer p | p= new int; // dynamically allocate an int for loading the address in p + To deallocate space dynamically use the delete operator to free up memory space. The syntax | of using thi delete var_name; > Simple program showing the concept of dynamic memory allocation: #include | using namespace std; | int main(){ | double* val = NULL; val = new double; val = 38184.26; cout << “Value is: “ << *val << endl, delete val;} @™™ 8. Program to illustrate dynamic allocation W/ and dealllocation of memory using new and delete Hinclude using namespace std; int main () f 1/ Pointer initialization to null int* p = NULL; / Request memory for the variable // using new operator p = new int: if (Ip) ’ cout << “allocation of memory failed’ else i 1 Store value at allocated address (69 } Rahul Publications B.Com. “p= 29; cout << “Value of p: " << *p << endl // Request block of memory //using new operator float *r = new float(75.25), cout << “Value of r: * << *r << endl; W/ Request block of memory of size n int *q = new int{n}; if (1p) cout << “allocation of memory failed\n’; else { for (int i= 0; — So the class is applicable at places where users should be able to add new attributes at runtime; — a user defined class but at runtime. > This mechanism is not supported directly in C++ as is in Smalltalk and CLOS. But it can be implemented in C++ using its static data and function members. The following program implements a meta class. 9. Program on Meta Class #include using namespace std; class a { metabaseobject(a) public: a () {cout << ‘aa Wy} virtual void prn() { cout << ‘a’: } X class b : public a { metaobject(b, a) public: b () {cout << “b::b Wn"; } virtual void prn() { cout << “bln; } XK class d { metabaseobject(d) public: d() { cout << “d:d Wns} virtual void pm() { cout << ‘d\n’; } BX class c : public d, puuiic 0 { metaobject2(c, d, b) public: ©) {cout << ‘cc Wn’; } 71} Rahul Publications B.Com. I YEAR IV SEMESTER virtual void prn() { cout << “c\n"; } b metaobjectdef(a); metaobjectdef(b); metaobjectdef(o); metaobjectdef(d); void main() { const metaclass ‘ma = a::meta(); ma = c::meta(); a *p = ma->newinstance(); p->prn(); delete p; p= (b*)new c; p->prn(); cout <inheritsfrom(c::meta()); cout <inheritsfrom(a::meta(); cout <objectisa(p) << endl; cout <typeinto().name() << endl; cout <typeinfo().name() << endl; delete p;} The output from this program should look like that: did a bb one © 017 metaclasses::a metaclasses::c Rahul Publications unit = tl OBJECT ORIENTED PROGRAMMING IN C++ Q16. What is an abstract class? Explain with an example. Ans: > Anabstract class is a class that is designed to be specifically used as a base class. > An abstract class contains at least one pure virtual function. You can declare a function by using a pure specifier (= 0) in the declaration of a virtual member fu class declaration. Example : The following is an example of an abstract class: class AB { ‘ public: virtual void {() = 0; Here virtual void {{) = 0, tells the compiler that the function is a pure virtual function The body is defined by its sub classes. 2.10.1 Pure Virtual Functions Q17. What is a pure virtual function ? Ana Pure virtual Functions are virtual functions with no definition. They start and ends with = 0. Here is the syntax for a pure virtual function, virtual void {( virtual keyw Mmm 10. Program on Pure Virtual Function / Abstract Class class Base WAbstract base class { public: virtual void show() = 0; {Pure Virtual Function h class Derived:public Base { public: void show() { cout << “Implementation of Virtual Function in Denved class & int main() { Base obj; Compile Time Error Base *b; Derived d; b= 8d; b->show(); } Output : Implementation of Virtual Funetion in Denived class C3} —— Rahal Pubiaions B.Com. ILYEAR_IV SEMESTER Short Question and Answers 1. Write a short note on Encapsulation. Ana: » — Encapsulation is an Object Oriented Programming concept that binds together the data and functions that manipulate the data. >» It also keeps both safe from outside interference and misuse. > Data encapsulation led to the important OOP concept of data hiding, 2. What is meant by Abstract Data Type? Aus Abstract Data type (ADT) is a type (or class) for objects whose behavior is defined by a set of value and a set of operations. The definition of ADT only mentions what operations are to be performed but not how these operations will be implemented. It does not specify how data will be organized in memory and what algorithms will be used for implementing the operations. 3. Explain syntax to declare a class ? Aas : The general form of a class declaration in: class class_name ( private: variable declarations; function declarations; public: variable declarations; function declaration; > The class declaration is similar to a struct declaration; the body of a class is enclosed within braces and terminated by a semicolon. > The class body contains the declaration of variables and functions. > These functions and variables are collectively called class members. (7a) 74 Rahul Publications ~ OBJECT ORIENTED PROGRAMMING IN C+* 4, _ Explain the syntax to create an object in C++, fuss Once a class has been declared, we can create variables of that type by using the class name as: Classname object name; For example, Rectangle rect; Rectangle is the class name (i.e., the data type), whereas rect was an object (variable of type class Rectangle) 5. | What is a constructor? Aue: Constructors are special member of a class. A constructor initializes object of a class. A C++, Constructor is automatically called when an object (an instance of the class) is created. > Ithas the same name of the class. > It must be a public member. > No Return Values. > — Default constructors are called when constructors are not defined for the classes. > Constructors can be defined either inside the class or outside class. 6. _ Explain types of constructors. Ana: Constructors are of three types : 1. Default Constructor 2 Parameterized Constructor 3. Copy Constructor 7. What is Copy Constructor? One of the more important forms of a constructor is the copy constructor. The purpose of the copy constructor is to initialize a new object with data copied from another object of the same class. For example to invoke a copy constructor the programmer writes Cube clic2); or Cube cl=c2; Both the above formats can be used to invoke a copy constructor. 75 Rahul Publications B.Com. I YEAR IV SEMESTER 8. What is destructor? Aus : Destructor is a special class function which destroys the object as soon as the scope of object ends, The destructor is called automatically by the compiler when the object goes ot't of scope. The syntax for destructor is same as that for the constructor, the class name is used for the name of destructor; with a tilde ~ sign as prefix to it class A { public: ~Al); ‘ Destructors will never have any arguments. 9. What is meant by garbage collection? Aus: > — Garbage collection is the recovery of computer storage that is being used by a program when that program no longer needs the storage. > Garbage collection is an automatic memory management feature in many modern programining languages, such as C++, Java and languages. > The programmer is responsible for ensuring that objects they created via new are deleted via delete. 10. Explain about DMA. Ans: ‘There are two ways via which memories can be allocated for storing data. 1. Compile time allocation or static allocation 2. Runtime allocation or dynamic allocation of memory. Programmers can dynamically allocate storage space while the program is running, dynamic allocation used in 2 steps: > — Creating the dynamic space in memory > Storing its address in a pointer (so that space can be accessed) @ Rahul Publications : oe OBJECT ORIENTED PROGRAMMING, a ‘ Choose the Correct Answer 1. which OOP concept binds data and functions together. lay (a) Abstraction (b) Inheritance (c) Encapsulation (d) Polymorphism 2, The functions and variables of a class are called as —__— fa) (a) classmembers (b) templates (c) args (d) params 3. ———— operator is called as scope resolution operator. [ec] la) is (b) ** (ce) (d) ?: 4. Aconstructor with one or more parameters is called — (d] (a) default constructor (b) copy constructor (c) new constructor (d) parameterized constructor 5. The special function which deallocates memory is [b] (a) constructor (b) destructor (c) object (d) method 6, —____ is the recovery of computer storage (c] (a) buffering (b) collecting (c) garabage collection (d) hashing 7. DMA means —____ fa] (a) Dynamic memory allocation (b) Direct memory allotment (c) Dynamic menu allocation (d) Direct merge allotment 8. operator is used to allocate space dynamically c (a) delete (b) that (c) new (d) this 9. Which class objects can themselves act as classes {a (a) friend (b} abstract (c) derived (d) meta 10. An abstract class contains atleast one (a) method (b) pure virtual function (c) constructor (4) destructor “7 vr Rahul Publications B.Com. MYEAR IV SEMESTER { Fill in the blanks ADT means _____. A_______ is way to bind the data and functions. By default all the members of a class have —___— access. Using of two or more constructors is called Member functions can be defined either ____— the class or the class, ‘A cpp class has public, private and ____— access. copies data from another object constructor. A destructor uses symbol ____ with same classname. 1 2 3 4 5. operators is used to deallocate memory. 6 7 8 9 1 0. keyword declares a virtual function, ANSWERS AbstractDataType class private constructor overloading i 2. 3. 4. 5. delete 6. inside, outside 7. protected 8. copy constructor 9. 10. virtual & ‘Rahul Publications EES TOmT TEER Top OPO OVERLOADING, CONVERSIONS, DERIVED CLASSES AND INHERITANCE: Function and Operator Overloading - Overloading Unary and Binary Operators - Data and Type Conversions - Derived Classes - Concept of Reusability - Visibility modes - Types of Inheritance - Single and Multiple Inheritance - Multilevel Inheritance. 3.1 INTRODUCTION TO FUNCTION AND OPERATOR OVERLOADING C++ allows you to specify more than one definition for a funetion name or an operator, which is called function overloading and operator overloading respectively When you callan overloaded function or operator, the compiler determines the most appropriate definition to use, the process of selecting the most appropriate overloaded function or operator is called overload resolution. 3.1.1 Function Overloading in C++ Ql. What is Function overloading? Aus: If any class has multiple functions with same names but different parameters then they are said to be overloaded. Function overloading allows you to use the same name for different functions, to perform, either same or different functions in the same class. Ways to overload a function: 1. By changing number of Arguments 2. By having different types of argument. Number of Arguments Different In this type of function overloading we define two functions with same names but different number of parameters of the same type. For example, in the below mentioned program we have made two sum() functions to return sum of two and three integers int sum (int x, int y){ cout << x+y; } int sum(int x, int y, int 2){ cout << x+y+z; } Here sum() function is overloaded, to have two and three arguments. Which sum() function will be called, depends on the number of arguments. Rahul Publicatio BCom! \ILYEAR IV SEMESTER, Wm 1. Program on function overloading - type 1 Mfunction overloading—different arguments : #include using namespace std; int sum (int x, int y) { cout <<“sum= "< — Unary Operators > — Binary Operators Unary Operator Overloading : “The unary operators operate on a single operand and following are the examples of Unary operators > The increment (++) and decrement (—) operators > The unary minus (-) operator. > The ‘ogical not (!) operator. Rahul Publications B.Com. ILYEAR IV SEMESTER The unary operators operate on the object for which they were called and normally, this operator appears on the left side of the object, as in !obj, -obj, and +-+obj but sometime they can be used as postfix as well ike obj++ or obj— Following example explain how minus (-) operator can be overloaded for prefix as well as postfix usage. mmm 3. Program on Unary Operators Overloading Hinclude using namespace std; class Distance { private: int feet; 0:0 infinite int inches; 10 t0 12 public: W required constructors Distance() { feet inches } Distance(int f, int i) { feet = f; inches =i; } 1 method to display distance void displayDistance() { cout << “F: * << feet <<“ |:" << inches < #include class Rectangle if int L,B; public: Rectangle() Default Constructor { i Rectangle(int x,int y) lParameterize Constructor { Lex Bry; } Rectangle operator+(Rectangle Rec) Binary operator overloading func. ft Rectangle R; RL=L+Recl; RB= B+ Rec; return Ry } | Rahul Publications B.Com. IYEAR IV SEMESTER void Display() i cout<<"initLength : *< Type Conversion is the process of converting one data type into another type —> Type Casting is the converting one predefined type into another typ forcefully. \ ‘Types of Type Conversions in C++ C++ facilitates type conversion into 2 forms: > Implicit Type Conversion | > Explicit Type Conversion Implicit Type Conversion Implicit Type Conversion is the conversion performed by tae compiler > Itis applied, whenever; different data types are intermixed in an expression, so as not to loose information. The C++ compiler converts all operands up to the type of the largest operand, which is called type promotion. After applying above arithmetic conversions, each pair f of erands is of same type and the yesult of each operation is the same as the type of both operands, Example of Implicit Type Conversion char ch. int, float fl double db, long doubie Id, resut= — (ch//i) + (db) - (lei) + (dee) | | 1 | int double ie [irene I U : int double float’ long double oe double T | double L_ : Rahul Publications 8.Com. ILYEAR_IV SEMESTER Alll the data types of the variables are upgraded to the data type of the variable with largest data type. bool -> char -> short int -> int -> unsigned int -> long -> unsigned -> Jong long -> float -> double -> long double Explicit Type Conversion > Explicit Type conversion is also called type casting. > It is the conversion of one operand to a specific type. >» — Anexplicit conversion is a user defined that forces to specific type Syntax : (type) expression Example : float(a+b/5) ; This expression evaluates to type float. Problem in Explicit Type Conversion Casting smaller data type to a larger data type, may not pose any problem. But, assigning a value of larger data type to smaller type forces data lose. Example for Type Casting int main (){ float x; x = (float) 7/5; / Casting integer to float cout<<"x="< using namespace std; int main) Uf float rest,res2; float f1=15.5, f float £3=5,f4 rest = (int)ftKintyf2; cout<<"casting float to intergerin’: couts<"resultt= “< Reusability is yet another important feature of OOP. > It would not only save time and money but also increase reliability. > Fortunately, C++ strongly supports the concept of reusability. The C++ classes can be re several ways. > — Once a class has been witten and tested, it can be adapted by other programmers to suit their requirements, > The mechanism of deriving a new class from an old one is called inheritance for derivation). The old class is referred to as the base class and the new one is called the derived class or subclass. Q6. a) ‘examples for derived classes. Ans : Inheritar.ce isa type of relationship. tinvolves sharing of attributes and operations among classes. d Abase class defines a set of common attributes and operations which it shares with d classes. A derived class extends the resources provided by the base class by adding its own data members and member functions. For example, noes] —— itera tiger cheetah _| (a7} Rahul Publications B.Com. ILYEAR_IV SEMESTER Q7. What is Inheritance? Aus Inheritance is the process, which allows a new class to be based on an existing class. The new class inherits all the member variables and functions (except the constructors and destructor) of the class on which it is based on. The existing classes can be called as Base classes and the new classes which are creating based on the existing classes are called as derived classes. For example, a programmer can create a base class named fruit and define derived classes as mango, orange, banana, etc. fruit mango orange banana Each of these derived classes, (mango, orange, banana, etc.) has all the features of the base class (fruit) with additional attributes or features specific to these newly created derived classes. Mango would have its own defined features, orange would have its own defined features, banana would have its own defined features, etc. 3.5.1 Defining a Derived Class Q8. Explain the syntax to define a subclas: Ans: ‘A derived class can be defined by specifying its relationship with the base class in addition to Its own details, The general form of defining a derived class is: class derived-class name : visibility-mode base-class name { // members of derived class >» — The colon indicates that the derived-class derived from the base-class. > The The default visibility-mode is private. isibility-mode is optional (either private or public). v Kad 6. Program on Inheritance #include using namespace std; / base class class Vehicle Rahul Publications unit - Il OBJECT ORIENTED PROGRAMMING IN C+* public: Vehicle() ic cout << “This is a Vehiale” << end! } “sub class derived from base classe class Car: public Vehicle( & main function int main() t 11 creating object of sub class will invoke the constructor of base classes Car obj; return 0; Q9. Explain about visibility modes of a classes (base class & derived class). Ana: > v of Public mode: If we derive a sub class from a public base class. Then the public member of the base class will become public in the derived class and protected members of the base class will become protected in derived class. Private members of the base class will never get inherited in sub class. Protected mode: If we derive a sub class from a Protected base class. Then both public member and protected members of the base class will become protected in derived class. Private members of the base class will never get inherited in sub class. Private mode: If we derive a sub class from a Private base class. Then both public member and protected members of the base class will become Private in derived class. Private members of the base class will never get inherited in sub class. The below table summarizes the above three modes and shows the access specifier of the members base class in the sub class when derived in public, protected and private modes: Derived Class Derived Class Derived Class. Baso class Public Mode Private Modo Protected Mode Private Protected vale Public Prva Rahul Publications B.Com. * el I_YEAR_IV SEMESTER 3.6.1 Public, Protected and Private Inheritance Q10. Explain Public, Protected and Private Inheritance in C++ - Ans: ne EC You can declare a derived class froma base class with different access co protected inheritance or private inheritance. trol, .e., public inheritance, #include using namespace std; class base { class derived : access_specifier base { }: Note: Either public, protected or private keyword is used in place of access_specifierterm used in the above code. Example of public, protected and private inheritance in C++ class base { public: int x; protected: int y; private: int, h class publicDerived: public base x is public / y is protected |/ zis not accessible from publicDerived 90 Rahul Publications UNIT - III OBJECT ORIENTED PROGRAMMING IN C++ class protectedDerived: protected base { J] xis protected I y is protected // 2 is not accessible from protectedDerived bf class privateDerived: private base { J) xs private /Iy is private J] zis not accessible from privateDerived } In the above example, we observe the following things: > base has three member variables: x, y andz which are public, protected and private member respectively. > — publicDerived inherits variables x and y as public and protected. z is not inherited as it is a private member variable of base. ed inherits variables x and y, Both variables become protected. z is not If we derive a class derivedFromProtectedDerived from protectedDerived, variables x and y are also inherited to the derived class. > privateDerived inherits variables x and y. Both variables become private. 2 is not inherited If we derive a class derivedFromPrivateDerived from privateDerived, variables x and y are not inherited because they are private variables of privateDerived Accessibility in Public Inheritance Accessibility private variables | protected variables | public variables Accessible from own class? yes yes yes Accessible from derived class? no, yes yes Accessible from 2nd derived class? no yes Accessibility in Protected Inheritance 4 private | protected . Accessibility Serie ||| eis public variables Accessible from own class? yes yes yes yes Accessible from derived class? no yes (inherited as protected variables) Accessible from 2nd derived class? no yes yes 7 Rahul Publications B.Com. Accessibility in Private Inheritance ILYEAR_IV SEMESTER Accessibility private variables | protected variables | _ public variables Accessible from own class? yes yes yes yes yes Accessible from derived class? no (inherited as private (inherited as variables) private variables) Accessible from 2nd derived class? no no no mm 7. C++ Program to illustrate access control in inheritance #include using namespace std; class Base { public: int i; void printValues() { cout << “Base: = "<< i << In” << "Base:ic = "<< 0 << tn" << ‘Based = "< using namespace std; class A Uf public. void show() { cout<<"called from base class A"< using namespace std; class B f public: void show() di cout<<‘called from base class B"< using namespace std; ILYEAR_IV SEMESTER class C { public: void disp() { : cout<<"called from base class C’< using namespace std; class G { public: @) Rahul Publications

You might also like